Monday 13 April 2015

Sum of consecutive squares (Palindrome) using c#

The palindromic number 595 is interesting because it can be written as the sum of consecutive squares: 62 + 72 + 82 + 92 + 102 + 112 + 122
Find the sum of all the numbers less than limit that are both palindromic and can be written as the sum of consecutive squares


static void Main(string[] args)
        {
            Console.WriteLine("Please enter the limit");
            int limit = 100;
            limit =Convert.ToInt32(Console.ReadLine());
           
             //Find square root limit for for the number we passed to avoid unnecessary loops
            double sqrtLimit = Math.Sqrt(limit);

            long sum = 0;
            //Create list to add list of consecutive number below limit
            List<int> list = new List<int>();

            Console.WriteLine();
            Console.WriteLine("Consecutive sum of squares palindrome from 1 to " + limit);

            //loop through square root limit
            for (int i = 1; i <= sqrtLimit; i++)
            {
                //Here for example if i is 1 then j must starts from 2
               //Because we summed the value of squares like 1^1 * 2^2
                int number = i * i;
                for (int j = i + 1; j <= sqrtLimit; j++)
                {
                    number += j * j;
                    //Suppose if the sum of number cross the  limit we entered should break this loop and                          //starts from next number
                    if (number > limit) break;
                   
                    //check sum of number is palindrome or not
                    //yes then add it to list else not
                    if (IsPalindrome(number) && !list.Contains(number))
                    {                      
                        sum += number;
                        list.Add(number);
                    }
                }
            }
           
            //sort the list for alphabetical order
            list.Sort();

            foreach (var val in list)
                Console.WriteLine(val);

            Console.ReadLine();
        }

        private static Boolean IsPalindrome(int number)
        {
            //covert number to string then convert it into char array
            var revNum = number.ToString().ToCharArray();
           //reverse the array
            Array.Reverse(revNum);
            return number == Convert.ToInt32(string.Join(",", revNum).Replace(",", string.Empty));
        }

Wednesday 11 December 2013

Pass json string data to Rest service (POST Method) using c#

Save Rescords with Rest Service POST Method in WCF Application using VS2008

Step 1 : Create a new WCF Service Application Project

Step 2 : Delete default service files like Service.svc & IService.cs

Step 3 : Then Add new WCF Service file. I added in the file name as RestServiceImpl.svc. Automatically                  IRestServiceImpl.cs file will be added.



Step 4 :  Open RestServiceImpl.cs file and also IRestServiceImpl.cs. In both files add the following codes                   respectively.

In RestServiceImpl.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Activation;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

namespace SampleRest
{
    // NOTE: If you change the class name "RestServiceImpl" here, you must also update the reference to "RestServiceImpl" in Web.config.
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class RestServiceImpl : IRestServiceImpl
    {
        string conStr = ConfigurationManager.ConnectionStrings["connRest"].ConnectionString;

        public string EchoWithGet(string s)
        {
            return "You said " + s;
        }

        public string EchoWithPost(string s)
        {
            return "You said " + s;
        }

        public string GetJSonString(jSonStr jsonData)
        {
            if (!string.IsNullOrEmpty(jsonData.jsonStr))
                return SaveJsontoDB(jsonData.jsonStr);
            else
                return "{\"success\":false}";
        }

        public string GetJSonData(jsonDataCollection jsonData)
        {            
            var res =JsonConvert.SerializeObject(jsonData);
            return SaveJsontoDB(res);
        }

        private string SaveJsontoDB(string oJson)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            StringBuilder sb = new StringBuilder();
            sb.Append("{\"jsonResult\":[{");

            using (SqlConnection con = new SqlConnection(conStr))
            {
                con.Open();
                var jSonData = serializer.Deserialize<jsonDataCollection>(oJson);
                foreach (var data in jSonData.jsonData)
                {
                    string query = "iPad_InsertLogDetails";
                    using (SqlCommand cmd = new SqlCommand(query, con))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@iUserId", data.user_Id);
                        cmd.Parameters.AddWithValue("@iAppId", data.app_id);

                        if (!string.IsNullOrEmpty(data.session_key) && data.session_key.Trim() != "")
                            cmd.Parameters.AddWithValue("@vSessionKey", data.session_key);

                        cmd.Parameters.AddWithValue("@vVersionName", data.app_version);

                        if (!string.IsNullOrEmpty(data.IPAddress) && data.IPAddress.Trim() != "")
                            cmd.Parameters.AddWithValue("@vIPAddress", data.IPAddress);

                        cmd.Parameters.AddWithValue("@iLogTypeID", data.log_typeId);
                        cmd.Parameters.AddWithValue("@iLogDesc", data.log_description);
                        cmd.Parameters.AddWithValue("@bIsOnline", data.app_isOnline);

                        try
                        {
                            cmd.ExecuteNonQuery();                            
                            sb.Append("{\"success\": true},");
                        }
                        catch (Exception ex)
                        {                            
                           // sb.Append("{\"log_Id\":" + Convert.ToString(data.log_Id) + ",\"success\":false,\"Error\":\"" + ex.Message.ToString() + "\"},");
                            sb.Append("{\"log_Id\":" + Convert.ToString(data.log_Id) + ",\"success\":false},");
                        }
                        cmd.Dispose();
                    }
                }
            }

            //sb.ToString().TrimEnd(',');
            sb.Remove(sb.Length - 1, 1);
            sb.Append("}]}");
            return JsonConvert.SerializeObject(sb.ToString());            
        }

        public class jsonDataResult
        {           
            public IEnumerable<Dictionary<string,object>> jsonResult { get; set; }
        }       
    }

}

And In IRestServiceImpl.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace SampleRest
{
    // NOTE: If you change the interface name "IRestServiceImpl" here, you must also update the reference to "IRestServiceImpl" in Web.config.
    //[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceContract]
    public interface IRestServiceImpl
    {     
        [OperationContract]           
        [WebInvoke(Method = "GET",ResponseFormat = WebMessageFormat.Xml,BodyStyle = WebMessageBodyStyle.Wrapped,UriTemplate = "/EchoWithGet/{s}")]
        string EchoWithGet(string s);

        [OperationContract]
        [WebInvoke(Method = "GET", UriTemplate = "/EchoWithPost/{s}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, 
            BodyStyle = WebMessageBodyStyle.Wrapped)]
        string EchoWithPost(string s);

        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "/GetJSonData", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, 
            BodyStyle = WebMessageBodyStyle.Bare)]
        string GetJSonData(jsonDataCollection jsonData);

        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "/GetJSonString", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, 
            BodyStyle = WebMessageBodyStyle.Bare)]
        string GetJSonString(jSonStr jsonStr);
    }

    [DataContract]
    public class jsonDataCollection
    {
        [DataMember]
        public IEnumerable<jSonData> jsonData { get; set; }
    }

    [DataContract]
    public class jSonData
    {
        [DataMember]
        public int log_Id { get; set; }

        [DataMember]
        public int user_Id { get; set; }

        [DataMember]
        public int app_id { get; set; }

        [DataMember]
        public string session_key { get; set; }

        [DataMember]
        public string app_version { get; set; }

        [DataMember]
        public string IPAddress { get; set; } 

        [DataMember]
        public int log_typeId { get; set; }

        [DataMember]
        public string log_description { get; set; }

        [DataMember]
        public bool app_isOnline { get; set; }

        [DataMember]
        public string app_dateTimeZone { get; set; }        
    }

    [DataContract]
    public class jSonStr
    {
        [DataMember]
        public string jsonStr { get; set; }
    }

}

Step 5 : After create this code add Newtonsoft.Json file in your bin folder and add reference to your project.

           Go to this link http://json.codeplex.com/ then choose downloads tab. Here you found file download link.

Step 6 : Working with rest service you have to change your web.config file.

   If you add any WCF Service file automatically service behavior created under Service Model. You slightly alter the code work with Rest service. 

<system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <services>
      <service behaviorConfiguration="SampleRest.RestServiceImplBehavior" name="SampleRest.RestServiceImpl">
        <endpoint address="http://localhost/RestServiceImpl.svc" binding="webHttpBinding" contract="SampleRest.IRestServiceImpl" behaviorConfiguration="Web">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors> 
      <serviceBehaviors>
        <behavior name="SampleRest.RestServiceImplBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="Web">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

In default endpoint binding should be in webHttpBinding. We need to alter this like webHttpBinding and then add endpointBehaviors tag under behavior. 

Step 7 : Now add new Web Application project.

Step 8 : In deault page add the following code.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SampleRestWeb._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server" Height="150" Width="300" TextMode="MultiLine"></asp:TextBox>
    </div>
    </form>
</body>
</html>

and in Default.aspx.cs page add the below code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;
//using HttpUtils;
using System.Web.UI.MobileControls;
using RestSharp;
using System.Web.Script.Services;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SampleRestWeb.ServiceReference1;
using System.Data.SqlClient;

namespace SampleRestWeb
{
    public partial class _Default : System.Web.UI.Page
    {
        jSonStr ojsonStr = new jSonStr();
        jsonDataCollection ojSonDataCol = new jsonDataCollection();

        protected void Page_Load(object sender, EventArgs e)
        {
            string jsonString = "{\"jsonData\":[{"
                        + "\"log_Id\" : 0,"
                        + "\"user_Id\" : 1249,"
                        + "\"session_key\" : \"dvnoewcdw\","
                        + "\"app_id\" : 1,"
                        + "\"app_version\" :\"1.2.7\","
                        + "\"app_isOnline\" : true,"
                        + "\"app_dateTimeZone\" : \"1997-07-16T19:20:30+01:00\","
                        + "\"log_typeId\" : 1,"
                        + "\"log_description\" : \"valid\"}"
                    + ",{"
                        + "\"log_Id\" : 1,"
                        + "\"user_Id\" : 1249,"
                        + "\"session_key\" : \"dvnoewcdw\","
                        + "\"app_id\" : 1,"
                        + "\"app_version\" : \"1.2.7\","
                        + "\"app_isOnline\" : true,"
                        + "\"app_dateTimeZone\" : \"1997-07-16T19:20:30+01:00\","
                        + "\"log_typeId\" : 2,"
                        + "\"log_description\" : \"syncing permissions successful\"}]}";
            
            const string url = "http://localhost:1307/RestServiceImpl.svc/";

            JavaScriptSerializer serializer = new JavaScriptSerializer(); 
            try
            {
                var client = new RestClient();
                // This, of course, needs to be altered to match the
                // IP Address/Port of the server to which you are connecting
                client.BaseUrl = url;
                var request = new RestRequest();
                //request.AddHeader("Content-Length", int.MaxValue.ToString());
                request.Method = Method.POST;
                request.RequestFormat = DataFormat.Json;               
                
                //Pass collection Data  Method 1
                ojSonDataCol = serializer.Deserialize<jsonDataCollection>(jsonString);
                request.AddBody(ojSonDataCol);
                request.Resource = "/GetJSonData";                 
                               
                //request.Resource = "/EchoWithGet/test"; 

                //Pass String Data Method 2
               // If you enable Method 2 comment Method 1 codes
                //ojsonStr.jsonStr = jsonString;
                //request.AddBody(ojsonStr);
                //request.Resource = "/GetJSonString";           
                
                // The server's Rest method will probably return something 
                var response = client.Execute(request) as RestResponse;
                
                if (response != null && ((response.StatusCode == HttpStatusCode.OK) &&
                 (response.ResponseStatus == ResponseStatus.Completed))) // It's probably not necessary to test both
                {                    
                    var obj = response.Content;
                    var res = JsonConvert.DeserializeObject(obj);
                    Response.Write(response.Content);                    
                }
                else if (response != null)
                {
                    Response.Write(string.Format
                    ("Status code is {0} ({1}); response status is {2}",response.StatusCode, response.StatusDescription, response.ResponseStatus));
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
    }
}

Step 9 : Download restsharp dll file under add it in your web project bin folder, then add reference into your project and also add Newtonsoft.json reference into your web project.

 Download the restsharp dll in https://github.com/restsharp/RestSharp/downloads (Please download latest version)

Step 10:  Now Add WCF Service reference into your web project. The project flow will be look like as








Tuesday 3 September 2013

Replace Classes to inline styles then convert to Excel or PDF

Here we are viewing elements inside the div tag or table. Then get the div or table element using jquery and then read all Class  names and convert it into inline styles, then pass it to server side through hidden field and then make process to convert as excel or pdf

In Design Page

   In design page add the following code

  <div style="float:right;">
                        <asp:Button ID="btnExport" runat="server" OnClick="btnExport_Click" CssClass="btn btnexcel" OnClientClick="return fnExportExcel();"/>
                        &nbsp;&nbsp;
                        <asp:Button ID="btnPDF" runat="server"  OnClick="btnPDF_Click" CssClass="btn btnPDF" OnClientClick="return fnExportPDF();"/>
                        &nbsp;&nbsp;
                        <input id="btnPrint" type="button" class="btn btnPrint" />
                    </div>
   <div id="divContent" style="display: none;">
                        <table cellpadding="0" cellspacing="0" style="width: 100%;" id="tblMain">
                            <tr>
                                <td align='left'>
                                    <table id="tblFundDtlView" cellspacing="0" class="tblGP">
                                        <tr>
                                           <td> ......</td>
                                        </tr>
                                            .
                                            .
                                            .
                                            .
                                    </table>
                                </td>
                            </tr>
                            <tr height="12">
                                <td>
                                 &nbsp;
                                </td>
                            </tr>
                            <tr>
                                <td align='left'>
                                    <div id="divtblGrid">
                                        <table id="tbl_Grid" border="0" cellspacing="0" width="100%">
                                            <tr>
                                             <td> ......</td>
                                            </tr>
                                            .
                                            .
                                            .
                                            .
                                        </table>
                                        <div id="pager">
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        </table>
                    </div>


In Script Add the following codes

<script type="text/javascript">
     //Export Functionalities
     //Button Export Functionalities
        function fnExportExcel() {
            var rowRemTbls = ["#tblFundDtlView"];
            exportData("#tblFundDtlView","Excel");
        }

        function fnExportPDF() {
            var rowRemTbls = ["#tblFundDtlView"];
            exportData("#tblFundDtlView", "PDF");
        }


 //Export To Excel and PDF Functionalities
   //<----------------------------Start----------------------------->

   function exportData(divName, conProc) {
        var html;
     
        html =$(ieInnerHTML($(divName)[0], false));
    
       $.each(html.find("* tr"), function() {
           if ($(this).css("display") == 'none') {
               $(this).remove();
           }
       });

       var retHTML;
       if (conProc == "Excel")
           retHTML = replaceClassToInline(html);
       else (conProc == "PDF")
           retHTML = html;       
     
       var emptyTable = $("<table><tr><td>&nbsp;</td></tr></table>");
       var cloneDiv = $("<div />").append(retHTML);
           
       retHTML = ieInnerHTML($(cloneDiv).html(), false);

       $("#ctl00_ContentPlaceHolder1_hidExportData").val("");
       $("#ctl00_ContentPlaceHolder1_hidExportData").val(encodeURIComponent(retHTML));
   }

   function replaceClassToInline(html) {
       var aStyleSheets = document.styleSheets;
       $.each(document.styleSheets, function(sheetIndex, sheet) {
           var sIndex = sheetIndex;
           $.each(sheet.cssRules || sheet.rules, function(ruleIndex, rule) {
               var ruleIndex = ruleIndex;
               var cssText;
               if (rule.cssText != undefined) {
                   cssText = rule.cssText.replace(/(\{|;)\s+/g, "\$1\n  ").replace(/\A\s+}/, "}").replace("}", "").split("{");
                   cssText = cssText[1];
               }
               else
                   cssText = $(rule).css("cssText");

               var selectorText = rule.selectorText;

               if ($.trim(selectorText).substr(0, 1) == "." && cssText != undefined && cssText != '') {
                   if (selectorText.indexOf("grad1") != -1)
                       var a = "";

                   $.each(selectorText.split('.'), function() {
                       if ($.trim(this) != '' && $.trim(this) != undefined) {
                           var cName = $.trim(this);
                           cName = cName.replace(',', '');
                           try {
                               $.each(cName.split('.'), function() {
                                   if ($.trim(this) != '' && $.trim(this) != undefined) {
                                       var rows;
                                       $.each(this.split(' '), function() {
                                           var conClass = $.trim(this);
                                           $.each(html.find("." + this), function() {
                                               if (cssText.indexOf('background: url("../images/table/Plus_min.png") no-repeat left 8px;') == -1)
                                                   cssText = cssText.replace('background: url("../images/table/Plus_min.png") no-repeat left 8px;', '');

                                               if ($(this).attr("style")) {
                                                   var style = $(this).attr("style") + ";" + cssText;
                                                   $(this).attr("style", style);
                                               }
                                               else {
                                                   $(this).attr("style", cssText);
                                               }

                                               $(this).css('height', '');

                                               $(this).removeClass(conClass);
                                           });
                                       });
                                   }
                               });
                           }
                           catch (e) { }
                       }
                   });
               }
           });
       }); 
       return html[0];
   }

   function ieInnerHTML(obj, convertToLowerCase) {
       var zz = obj.innerHTML ? String(obj.innerHTML) : obj
       , z = zz.match(/(<.+[^>])/g);

       if (z) {
           for (var i = 0; i < z.length; (i = i + 1)) {
               var y
         , zSaved = z[i]
         , attrRE = /\=[a-zA-Z\.\:\[\]_\(\)\&\$\%#\@\!0-9\/]+[?\s+|?>]/g;

               z[i] = z[i]
              .replace(/([<|<\/].+?\w+).+[^>]/,
                 function(a) {
                     //return a.toLowerCase();
                     return a;
                 });
               y = z[i].match(attrRE);

               if (y) {
                   var j = 0
           , len = y.length
                   while (j < len) {
                       var replaceRE =
               /(\=)([a-zA-Z\.\:\[\]_\(\)\&\$\%#\@\!0-9\/]+)?([\s+|?>])/g
             , replacer = function() {
                 var args = Array.prototype.slice.call(arguments);
                 return '="' + (convertToLowerCase ? args[2].toLowerCase() : args[2]) + '"' + args[3];
                 //return '="' + args[2] + '"' + args[3];
             };
                       z[i] = z[i].replace(y[j], y[j].replace(replaceRE, replacer));
                       j += 1;
                   }
               }
               zz = zz.replace(zSaved, z[i]);
           }
       }
       return zz;
   }
  
 </script>


Then in .cs Page Add the following code

protected void btnExport_Click(object sender, EventArgs e)
        {
            exportToExcel(hidExportData.Value.Trim());
            hidExportData.Value = "";
        }

        protected void btnPDF_Click(object sender, EventArgs e)
        {
            exportToPDF(hidExportData.Value.Trim());
            hidExportData.Value = "";
        }


public void exportToPDF(string html)
        {
            string strHTML = Regex.Replace(HttpContext.Current.Server.UrlDecode((html)), @"\s+", " ");
            strHTML = Regex.Replace(strHTML, "</?(a|A).*?>", "");
            strHTML = strHTML.Replace("Loading...", "");
            strHTML = strHTML.Replace("javascript:void(0)", "#");
            ////reset response
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = "application/pdf";

            ////define pdf filename
            string strFileName = "Report.pdf";
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);

            //get html
            string outXml = strHTML;

            //Generate PDF
            using (Document document = new Document((PageSize.TABLOID), 10, 10, 10, 10))
            {
                //define output control HTML
                MemoryStream memStream = new MemoryStream();
                TextReader xmlString = new StringReader(outXml);

                PdfWriter writer = PdfWriter.GetInstance(document, memStream);

                //open doc
                document.Open();

                HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
                htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
                //htmlContext.SetImageProvider(new ImageProvider());

                ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
                cssResolver.AddCssFile(HttpContext.Current.Server.MapPath("~/css/ExportCss.css"), true);
                //cssResolver.AddCssFile(Server.MapPath("~/css/common.css"), true);
                cssResolver.AddCssFile(HttpContext.Current.Server.MapPath("~/css/ui.jqgrid.css"), true);
                cssResolver.AddCssFile(HttpContext.Current.Server.MapPath("~/css/custom-theme/jquery-ui-1.10.3.custom.min.css"), true);

                IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));
                XMLWorker worker = new XMLWorker(pipeline, true);
                XMLParser xmlParse = new XMLParser(true, worker);
                xmlParse.Parse(xmlString);
                xmlParse.Flush();

                document.Close();
                document.Dispose();

                HttpContext.Current.Response.BinaryWrite(memStream.ToArray());
            }

            HttpContext.Current.Response.End();
            HttpContext.Current.Response.Flush();
        }

        public void exportToExcel(string strHTML)
        {
            String html = stringBuilder.Append(Regex.Replace(HttpContext.Current.Server.UrlDecode((strHTML)), @"\s+", " ")).ToString();

            html = Regex.Replace(html, "</?(a|A).*?>", "");
            html = html.Replace("Loading...", "");
            html = html.Replace("javascript:void(0)", "#");

            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=Report.xls");
            HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            HttpContext.Current.Response.Write(html);
            HttpContext.Current.Response.End();
        }


After that download the follwing dll and extract it to your project bin folder then add reference of those dll files

links are:


Note : In both links download the latest versions

Tuesday 27 August 2013

JQGrid demo with custom Insert, Update and delete operations

In .aspx page

 Add the following scripts and CSS in design page

   <script src="../js/jquery.min.js" type="text/javascript"></script>
   <script src="../js/json2.js" type="text/javascript"></script>
   <script src="../js/JQGrid/jquery-ui-1.10.2.custom.js" type="text/javascript"></script>
   <script src="../js/JQGrid/jquery.jqGrid.js" type="text/javascript"></script>
   <script type="text/javascript" src="../js/JQGrid/i18n/grid.locale-en.js"></script>

  <link href="../jqCss/css/custom-theme/jquery-ui-1.10.3.custom.min.css" rel="stylesheet" />
  <link href="../CSS/ui.jqgrid.css" rel="stylesheet" />


Inside script tag add the following function

  <script type="text/javascript">
        $(function () {
            $("#<%= btnSaveUsr.ClientID %>").button().css("font-size", "12");
            $("#<%= btnINUsrEdit.ClientID %>").button().css("font-size", "12");
            $("#<%= btnCancelEdit.ClientID %>").button().css("font-size", "12");
            $("#<%= btnSaveEdit.ClientID %>").button().css("font-size", "12");
            $("#<%= btnSaveSentEdit.ClientID %>").button().css("font-size", "12");
            $("#<%= btnSaveandSend.ClientID %>").button().css("font-size", "12");
            $("#<%= btnCancelSent.ClientID %>").button().css("font-size", "12");
            $("#<%= btnSaveSent.ClientID %>").button().css("font-size", "12");
        });

        jQuery(document).ready(function () {
            jQuery('#datalist').jqGrid({
                url: '../WebServices/InternalUser.asmx/fillInternaluser',
                editurl: '../WebServices/InternalUser.asmx/fillInternaluser',
                mtype: 'POST',
                datatype: 'json',
                postData: { Action: 'Fill' },
                ajaxGridOptions: { cache: false },
                page: 1,
                colNames: ['UserID', 'First Name', 'Last Name', 'Title', 'Email', 'Password', 'Special Password', 'Forgot Password Question?'
                    , 'Forgot Password Answer?', 'Phone', 'Mobile', 'Permitted Login(s)', 'Buyer Code', 'Notes', '', ''],
                colModel: [
                        {
                            name: 'CLUM_Id', index: 'CLUM_Id', sortable: true,
                            align: 'left', key: true, editable: true, editrules: { edithidden: false }, hidedlg: true, hidden: true, frozen: true
                        },
                        {
                            name: 'CLUM_FirstName', sortable: true, align: 'left',
                            editable: true, editrules: { required: true }, formoptions: { elmsuffix: ' *' }, searchoptions: {}, frozen: true//, editoptions: { readonly: true }
                            , searchoptions: { sopt: ['eq', 'ne'], odata: ['Equal', 'Not Equal'] }
                        },
                        {
                            name: 'CLUM_LastName', sortable: true, align: 'left',
                            editable: true, editrules: { required: true }, formoptions: { elmsuffix: ' *' }, searchoptions: { sopt: ['eq', 'ne'], odata: ['Equal', 'Not Equal'] }
                        },
                        {
                            name: 'CLUM_Title', sortable: true, align: 'left',
                            editable: true, editrules: { required: true }, formoptions: { elmsuffix: ' *' }, searchoptions: { sopt: ['eq', 'ne'], odata: ['Equal', 'Not Equal'] }
                        },
                        {
                            name: 'CLUM_email', sortable: true, align: 'left', formatter: 'mail', editable: true, width: 180,
                            edittype: 'text', editrules: { required: true, email: true }, formoptions: { elmsuffix: ' *' }, searchoptions: { sopt: ['eq', 'ne'], odata: ['Equal', 'Not Equal'] }
                        },
                        {
                            name: 'CLUM_Password', index: 'CLUM_Password', formatter: 'password', edittype: 'password', sortable: true,
                            align: 'left', editable: true, editrules: { required: true, edithidden: true }, formoptions: { elmsuffix: ' *' }, hidedlg: false, hidden: true
                            , searchoptions: { sopt: ['eq', 'ne'], odata: ['Equal', 'Not Equal'] }
                        },
                        {
                            name: 'CLUM_SpecialPassword', index: 'CLUM_SpecialPassword', formatter: 'password', edittype: 'password', sortable: true,
                            align: 'left', editable: true, editrules: { required: true, edithidden: true }, formoptions: { elmsuffix: ' *' }, hidedlg: false, hidden: true
                            , searchoptions: { sopt: ['eq', 'ne'], odata: ['Equal', 'Not Equal'] }
                        },
                        {
                            name: 'CLUM_FrgtPwd_Ques', index: 'CLUM_FrgtPwd_Ques', sortable: true,
                            align: 'left', editable: true, editrules: { required: true, edithidden: true }, formoptions: { elmsuffix: ' *' }, hidedlg: false, hidden: true
                            , searchoptions: { sopt: ['eq', 'ne'], odata: ['Equal', 'Not Equal'] }
                        },
                        {
                            name: 'CLUM_FrgtPwd_Ans', index: 'CLUM_FrgtPwd_Ans', sortable: true,
                            align: 'left', key: true, editable: true, editrules: { required: true, edithidden: true }, formoptions: { elmsuffix: ' *' }, hidedlg: false, hidden: true
                            , searchoptions: { sopt: ['eq', 'ne'], odata: ['Equal', 'Not Equal'] }
                        },
                        {
                            name: 'CLUM_Phone', width: 100,  align: 'left', searchoptions: { sopt: ['eq', 'ne'], odata: ['Equal', 'Not Equal'] },
                            editable: true, editrules: { required: true }, formoptions: { elmsuffix: ' *' },sortable: false
                        },
                        {
                            name: 'CLUM_Mobile',  align: 'left', searchoptions: {},
                            editable: true, editrules: { required: true }, formoptions: { elmsuffix: ' *' },sortable: false
                        },
                        {
                            name: 'CLUM_PermittedLogin', index: 'CLUM_PermittedLogin', searchoptions: { sopt: ['eq', 'ne'], odata: ['Equal', 'Not Equal'] }, sortable: true,
                            align: 'left', editable: true, editrules: { required: true, edithidden: true }, formoptions: { elmsuffix: ' *' }, hidedlg: false, hidden: true
                        },
                        {
                            name: 'CLUM_BuyerCode', index: 'CLUM_BuyerCode', searchoptions: { sopt: ['eq', 'ne'], odata: ['Equal', 'Not Equal'] }, sortable: true,
                            align: 'left', editable: true, editrules: { required: true, edithidden: true }, formoptions: { elmsuffix: ' *' }, hidedlg: false, hidden: true
                        },
                        {
                            name: 'CLUM_Notes', index: 'CLUM_Notes', searchoptions: { sopt: ['eq', 'ne'], odata: ['Equal', 'Not Equal'] }, sortable: true,
                            align: 'left', editable: true, editrules: { edithidden: true }, hidedlg: false, hidden: true
                        },
         {
                            name: 'SendEmail', index: 'SendEmail', sortable: false, width: 180, searchoptions: { sopt: ['eq', 'ne'], odata: ['Equal', 'Not Equal'] }
                        },
                        {
                            name: 'Activate', index: 'Activate', sortable: false, searchoptions: { sopt: ['eq', 'ne'], odata: ['Equal', 'Not Equal'] }
                        }
                        //,{
                        //    name: 'data_solicit_vale', index: 'data_solicit_vale', width: 95, align: 'center', sorttype: 'date',

                        //    formatter: 'date', formatoptions: { srcformat: 'd/m/Y H:i', newformat: 'd/m/Y H:i' }
                        //}
                ],
                viewrecords: true,
                scrollrows: true,
                prmNames: { id: "CLUM_Id" },
                headertitles: true,
                pager: jQuery('#pager1'),
                altRows: true,
                loadError: jqGrid_aspnet_loadErrorHandler,
                hoverrows: false,
                rowNum: 10,
                rowList: [10, 20, 30],
                gridview: true,
                editDialogOptions: {
                    closeOnEscape: true, recreateForm: true, closeAfterEdit: true, closeAfterAdd: true, reloadAfterSubmit: false, errorTextFormat: function (data) {
                        return 'Error: ' + data.responseText
                    },
                    editData: {
                        __RequestVerificationToken: jQuery('input[name=__RequestVerificationToken]').val()
                    }
                },
                addDialogOptions: {
                    closeOnEscape: true, recreateForm: true, closeAfterEdit: true, closeAfterAdd: true, reloadAfterSubmit: false, errorTextFormat: function (data) {
                        return 'Error: ' + data.responseText
                    },
                    editData: { __RequestVerificationToken: jQuery('input[name=__RequestVerificationToken]').val() }
                },
                delDialogOptions: {
                    closeOnEscape: true, recreateForm: true, closeAfterEdit: true, closeAfterAdd: true, reloadAfterSubmit: false,
                    errorTextFormat: function (data) {
                        return 'Error: ' + data.responseText
                    },
                    delData: {
                        __RequestVerificationToken: jQuery('input[name=__RequestVerificationToken]').val()
                    }
                },
                searchDialogOptions: {
                    closeOnEscape: true, recreateForm: true, closeAfterEdit: true, closeAfterAdd: true, reloadAfterSubmit: false, resize: false
                },
                 jsonReader: {
                    page: "page",
                    total: "total",
                    records: "records",
                    root: "rows",
                    //repeatitems: false,
                    id: "id"
                },
                sortorder: 'asc',
                sortname: 'CLUM_Id',
                shrinkToFit: true,
                width: 900,
                height: 'auto',
                viewsortcols: [true, 'vertical', true]
                    , gridComplete: function () {
                        var ids = jQuery("#datalist").jqGrid('getDataIDs');
                        for (var i = 0; i < ids.length; i++) {
                            var cl = ids[i];
                            //be = "<a href='' onclick=\"return fun_ViewEditClick(this);\">View/Edit</a>";
                            // jQuery("#datalist").jqGrid('setRowData', ids[i], { ViewEdit: be });
                            se = "<a href='' onclick=\"return fun_SendMailClick(this," + ids[i] + ");\" id='lnkSendMail" + ids[i] + "'>Send email with key</a>";
                            jQuery("#datalist").jqGrid('setRowData', ids[i], { SendEmail: se });
                            if ($("#<%= hidUsersView.ClientID %>").val() == "" || $("#<%= hidUsersView.ClientID %>").val() == "ActiveUser")
                                ce = "<a href='' onclick=\"return fun_ActiveInActive(this,this.innerHTML," + ids[i] + ");\">Inactivate</a>";
                            else
                                ce = "<a href='' onclick=\"return fun_ActiveInActive(this,this.innerHTML," + ids[i] + ");\">Activate</a>";

                            jQuery("#datalist").jqGrid('setRowData', ids[i], { Activate: ce });
                        }
                    },
                //ondblClickRow: function (id, ri, ci) {
                //    // edit the row and save it on press "enter" key
                //    //jQuery('#datalist').jqGrid('editRow', id, true, null, null, 'clientArray');
                //    var rowid = jQuery("#datalist").jqGrid('getGridParam', 'selrow');
                //    ShowEditRowData(this, rowid, true, "Edit");
                //},
                onSelectRow: function (id, status) {
                    var rowid = jQuery("#datalist").jqGrid('getGridParam', 'selrow');
                    ShowEditRowData(this, rowid, false, "View");
                },
                onSortCol: function (index, columnIndex, sortOrder) {
                    $('#datalist').jqGrid('setGridParam', { postData: { Action: "Fill" } });
                }
                //,search: {
                //    caption: "Search...",
                //    Find: "Find",
                //    Reset: "Reset",
                //    //odata: ['equal', 'not equal', 'less', 'less or equal', 'greater', 'greater or equal', 'begins with', 'does not begin with', 'is in', 'is not in', 'ends with', 'does not end with', 'contains', 'does not contain'],
                //    odata: ['equal', 'not equal'],
                //    groupOps: [{ op: "AND", text: "all" }, { op: "OR", text: "any" }],
                //    matchText: " match",
                //    rulesText: " rules"
                //}
                //edit: {
                //    addCaption: "Add Record",
                //    editCaption: "Edit Record",
                //    bSubmit: "Submit",
                //    bCancel: "Cancel",
                //    bClose: "Close",
                //    saveData: "Data has been changed! Save changes?",
                //    bYes: "Yes",
                //    bNo: "No",
                //    bExit: "Cancel"
                //},
                //view: {
                //    caption: "View Record",
                //    bClose: "Close"
                //},
                //del: {
                //    caption: "Delete Record",
                //    msg: "Delete selected record(s)?",
                //    bSubmit: "Delete",
                //    bCancel: "Cancel"
                //},
                //nav: {
                //    edittext: "",
                //    edittitle: "Edit selected row",
                //    addtext: "",
                //    addtitle: "Add new row",
                //    deltext: "",
                //    deltitle: "Delete selected row",
                //    searchtext: "",
                //    searchtitle: "Find records",
                //    refreshtext: "",
                //    refreshtitle: "Reload Grid",
                //    alertcap: "Warning",
                //    alerttext: "Please, select row",
                //    viewtext: "",
                //    viewtitle: "View selected row"
                //}
            })
                .navGrid('#pager1', {
                    edit: false, add: false, del: false, search: false, refresh: false, view: false, position: 'left', cloneToTop: false, reloadAfterSubmit: true
                    //,edittext: 'Edit',deltext: 'Delete',searchtext: 'Search',refreshtext: 'Reload', viewtext: 'View'
                },
                jQuery('#datalist').getGridParam('editDialogOptions'),
                jQuery('#datalist').getGridParam('addDialogOptions'),
                jQuery('#datalist').getGridParam('delDialogOptions'),
                jQuery('#datalist').getGridParam('searchDialogOptions')).bindKeys();
            //jQuery("#datalist").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false });
            $("#datalist").jqGrid("setLabel", "CLUM_Title", "", { "text-align": "left" });
            jQuery("#datalist").jqGrid('setFrozenColumns');

            function jqGrid_aspnet_loadErrorHandler(xht, st, handler) {
                jQuery(document.body).css('font-size', '100%');
                jQuery(document.body).html(xht.responseText);
            };

            //jQuery('#datalist').navButtonAdd('#pager1', {
            //    caption: "View",
            //    title: "Create new log entry",
            //    buttonicon: "ui-icon-show",
            //    onClickButton: function () {
            //        //editRecords();
            //        //alert("You can add your function here");
            //    },
            //    position: "first"
            //});

            //jQuery('#datalist').navButtonAdd('#pager1', {
            //    caption: "Reload",
            //    title: "Create new log entry",
            //    buttonicon: "ui-icon-refresh",
            //    onClickButton: function () {
            //        //editRecords();
            //        //alert("You can add your function here");
            //    },
            //    position: "first"
            //});

            //jQuery('#datalist').navButtonAdd('#pager1', {
            //    caption: "Search",
            //    title: "Create new log entry",
            //    buttonicon: "ui-icon-search",
            //    onClickButton: function () {
            //        //editRecords();
            //        //alert("You can add your function here");
            //    },
            //    position: "first"
            //});

            //jQuery('#datalist').navButtonAdd('#pager1', {
            //    caption: "Delete",
            //    title: "Create new log entry",
            //    onClickButton: function () {
            //        //editRecords();
            //        //alert("You can add your function here");
            //    },
            //    position: "first"
            //});

            //jQuery('#datalist').navButtonAdd('#pager1', {
            //    caption: "Edit",
            //    title: "Create new log entry",
            //    buttonicon: "ui-icon-pencil",
            //    onClickButton: function () {
            //        //editRecords();
            //        //alert("You can add your function here");
            //    },
            //    position: "first"
            //});

            jQuery('#datalist').navButtonAdd('#pager1', {
                id: "CbtnAdd",
                caption: "Add",
                title: "Create new log entry",
                buttonicon: "ui-icon-plus",
                onClickButton: function () {
                    ShowEditRowData(this, null, true, 'Add');
                },
                position: "first"
            });

            //jQuery('#datalist').jqGrid('navButtonAdd', '#pager1', {
            //    id: 'pager_excel', caption: '', title: 'Export To Excel',
            //    buttonicon: 'ui-icon-newwin',
            //    onClickButton: function () {
            //        ExportDataTo(this, 'Excel');
            //    }
            //});

            function ExportDataTo(obj, convertType) {
                var msg = "";
                var lnkVal = $("#<%= lnkViewUsers.ClientID %>").html();

                if (lnkVal == "View Inactive users") {
                    $("#MainContent_hidUsersView").val("InactiveUser")
                    msg = "ActiveUser";
                }
                else {
                    $("#MainContent_hidUsersView").val("ActiveUser");
                    msg = "InactiveUser";
                }

                window.open('../Ajax/ExportToExcel.aspx?ct=' + convertType + '&s=' + msg, '', 'resizable=yes,width=200,height=50')

                //$.ajax({
                //    type: "POST",
                //    url: "../WebServices/WS_ExportData.asmx/ExportData",
                //    data: JSON.stringify({ formatType: convertType, status: msg }),
                //    contentType: "application/json; charset=utf-8",
                //    dataType: "json",
                //    success: function (response) {
                //        var tableToExcel = (function () {
                //        var uri = 'data:application/vnd.ms-excel;base64,'
                //          , template =response.d
                //          , base64 = function (s) {return window.btoa(unescape(encodeURIComponent(s)));}
                //          , format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) };

                //        var encodestr = btoa(unescape(encodeURIComponent(response.d)));

                //           var ctx = { worksheet: 'Report' || 'Worksheet', table: response.d };
                //           window.location.href = uri + base64(format(template));
                //        })();
                //    },
                //    error: function (data, status, jqXHR) { alert("FAILED:" + status); }
                //});
            }

            function ShowEditRowData(source, rowID, vis, proc) {
                $('#<%= hidIsInsert.ClientID %>').val(proc);
                if (proc == "View" || proc == "Edit" || proc == "Add") {
                    clearData();
                    setVisibility(vis, proc);
                    fun_ViewEditClick(this);
                    //alert(rowID);
                    if (rowID != null) {
                        var $td = $('#datalist').jqGrid('getRowData', rowID);
                        $('#<%= txt_FirstName.ClientID %>').val($.trim($td["CLUM_FirstName"]));
                        $('#<%= lbl_FirstName.ClientID %>').text($.trim($td["CLUM_FirstName"]));

                        $('#<%= txt_LastName.ClientID %>').val($.trim($td["CLUM_LastName"]));
                        $('#<%= lbl_LastName.ClientID %>').text($.trim($td["CLUM_LastName"]));

                        $('#<%= txt_Title.ClientID %>').val($.trim($td["CLUM_Title"]));
                        $('#<%= lbl_Title.ClientID %>').text($.trim($td["CLUM_Title"]));

                        $('#<%= txt_EMail.ClientID %>').val($.trim($td["CLUM_email"]));
                        $('#<%= lbl_EMail.ClientID %>').text($.trim($td["CLUM_email"]));

                        $('#<%= txt_Pwd.ClientID %>').val($.trim($td["CLUM_Password"]));
                        $('#<%= lbl_Pwd.ClientID %>').text($.trim($td["CLUM_Password"]));

                        $('#<%= txt_SplPwd.ClientID %>').val($.trim($td["CLUM_SpecialPassword"]));
                        $('#<%= lbl_SplPwd.ClientID %>').text($.trim($td["CLUM_SpecialPassword"]));

                        $('#<%= txt_ForgetQuest.ClientID %>').val($.trim($td["CLUM_FrgtPwd_Ques"]));
                        $('#<%= lbl_ForgetQuest.ClientID %>').text($.trim($td["CLUM_FrgtPwd_Ques"]));

                        $('#<%= txt_ForgetQuestAns.ClientID %>').val($.trim($td["CLUM_FrgtPwd_Ans"]));
                        $('#<%= lbl_ForgetQuestAns.ClientID %>').text($.trim($td["CLUM_FrgtPwd_Ans"]));

                        $('#<%= txt_PhoneNo.ClientID %>').val($.trim($td["CLUM_Phone"]));
                        $('#<%= lbl_PhoneNo.ClientID %>').text($.trim($td["CLUM_Phone"]));

                        $('#<%= txt_MobileNo.ClientID %>').val($.trim($td["CLUM_Mobile"]));
                        $('#<%= lbl_MobileNo.ClientID %>').text($.trim($td["CLUM_Mobile"]));

                        $('#<%= txt_Notes.ClientID %>').val($.trim($td["CLUM_Notes"]));
                        $('#<%= lbl_Notes.ClientID %>').text($.trim($td["CLUM_Notes"]));

                        fun_ChkCheckboxStatus();
                    }
                    //else {
                    //     jQuery("#dialogSelectRow").dialog();
                    // }
                    return false;
                }
            }

            $("#<%= btnINUsrEdit.ClientID %>").click(function () {
                setVisibility(true, 'Edit');
                $('#<%= hidIsInsert.ClientID %>').val("Update");
                return false;
            });

            function setVisibility(vis, proc) {
                var lblVis = vis ? "none" : "block";
                var txtVis = vis ? "block" : "none";

                $('#<%= txt_FirstName.ClientID %>').css("display", txtVis);
                $('#<%= lbl_FirstName.ClientID %>').css("display", lblVis);

                $('#<%= txt_LastName.ClientID %>').css("display", txtVis);
                $('#<%= lbl_LastName.ClientID %>').css("display", lblVis);

                $('#<%= txt_Title.ClientID %>').css("display", txtVis);
                $('#<%= lbl_Title.ClientID %>').css("display", lblVis);

                $('#<%= txt_EMail.ClientID %>').css("display", txtVis);
                $('#<%= lbl_EMail.ClientID %>').css("display", lblVis);

                $('#<%= txt_Pwd.ClientID %>').css("display", txtVis);
                $('#<%= lbl_Pwd.ClientID %>').css("display", lblVis);

                $('#<%= txt_SplPwd.ClientID %>').css("display", txtVis);
                $('#<%= lbl_SplPwd.ClientID %>').css("display", lblVis);

                $('#<%= txt_ForgetQuest.ClientID %>').css("display", txtVis);
                $('#<%= lbl_ForgetQuest.ClientID %>').css("display", lblVis);

                $('#<%= txt_ForgetQuestAns.ClientID %>').css("display", txtVis);
                $('#<%= lbl_ForgetQuestAns.ClientID %>').css("display", lblVis);

                $('#<%= txt_PhoneNo.ClientID %>').css("display", txtVis);
                $('#<%= lbl_PhoneNo.ClientID %>').css("display", lblVis);

                $('#<%= txt_MobileNo.ClientID %>').css("display", txtVis);
                $('#<%= lbl_MobileNo.ClientID %>').css("display", lblVis);

                $('#<%= txt_Notes.ClientID %>').css("display", txtVis);
                $('#<%= lbl_Notes.ClientID %>').css("display", lblVis);

                if (proc == "View") {
                    $('#<%= btnSaveUsr.ClientID %>').css("display", "none");
                    $('#<%= btnINUsrEdit.ClientID %>').css("display", "block");
                    $('#<%= btnCancelEdit.ClientID %>').css("display", "block");
                    $('#<%= btnSaveEdit.ClientID %>').css("display", "none");
                    $('#<%= btnSaveSentEdit.ClientID %>').css("display", "none");
                    $("#<%= btnSaveandSend.ClientID %>").css("display", "none");
                    $("#<%= chk_celesticaBuyer.ClientID %>").attr("disabled", true);
                    $("#<%= chk_CelPurManager.ClientID %>").attr("disabled", true);
                    $("#<%= ddl_BuyCode.ClientID %>").attr("disabled", true);
                }
                else if (proc == "Add") {
                    $('#<%= btnSaveUsr.ClientID %>').css("display", "block");
                    $('#<%= btnINUsrEdit.ClientID %>').css("display", "none");
                    $('#<%= btnCancelEdit.ClientID %>').css("display", "block");
                    $('#<%= btnSaveEdit.ClientID %>').css("display", "none");
                    $('#<%= btnSaveSentEdit.ClientID %>').css("display", "none");
                    $("#<%= btnSaveandSend.ClientID %>").css("display", "block");
                    $("#<%= chk_celesticaBuyer.ClientID %>").removeAttr("disabled");
                    $("#<%= chk_CelPurManager.ClientID %>").removeAttr("disabled");
                    $("#<%= ddl_BuyCode.ClientID %>").removeAttr("disabled");
                }
                else if (proc == "Edit") {
                    $('#<%= btnSaveUsr.ClientID %>').css("display", "none");
                    $('#<%= btnINUsrEdit.ClientID %>').css("display", "none");
                    $('#<%= btnCancelEdit.ClientID %>').css("display", "block");
                    $('#<%= btnSaveEdit.ClientID %>').css("display", "block");
                    $('#<%= btnSaveSentEdit.ClientID %>').css("display", "block");
                    $("#<%= btnSaveandSend.ClientID %>").css("display", "none");
                    $("#<%= chk_celesticaBuyer.ClientID %>").removeAttr("disabled");
                    $("#<%= chk_CelPurManager.ClientID %>").removeAttr("disabled");
                    $("#<%= ddl_BuyCode.ClientID %>").removeAttr("disabled");
                    //fun_ChkCheckboxStatus();
                }
                //$("#lnk_AssApplBuyerCodes").attr('disabled', 'disabled');
                // $("#sLbtnFirst").removeAttr("href");
                // return false;
            }

            function fun_ChkCheckboxStatus() {
                var rowid = jQuery("#datalist").jqGrid('getGridParam', 'selrow');
                var $td = $('#datalist').jqGrid('getRowData', rowid);
                var perLogin = $.trim($td["CLUM_PermittedLogin"]);
                var buyerCode = $.trim($td["CLUM_BuyerCode"]).split(',');
                $('#<%= ddl_BuyCode.ClientID %>').val("0");

                if (perLogin != "") {
                    var arr = perLogin.split(',');
                    for (var i = 0; i < arr.length; i++) {
                        if (parseInt(arr[i]) == 2) {
                            $('#<%= chk_celesticaBuyer.ClientID %>').prop('checked', true);
                            // $('#<%= chk_celesticaBuyer.ClientID %>').attr("checked", 'checked');
                            // $('#<%= chk_celesticaBuyer.ClientID %>').click();

                            //$('#chkbxl_BuyCode input[type=checkbox]').each(function () {
                            //    //if ($(this).is(':checked')) {
                            //    //     buyerCode += $(this).val() + ",";
                            //    //     alert(buyerCode);
                            //    // }
                            //    var found = $.inArray($.trim($(this).val()), buyerCode) > -1;
                            //    if (found)
                            //        $(this).prop('checked', true);
                            //});

                            // var buyerCode = $('#<%= ddl_BuyCode.ClientID %>').val();
                            $('#<%= ddl_BuyCode.ClientID %>').val(buyerCode);
                        }
                        else if (parseInt(arr[i]) == 3) {
                            $('#<%= chk_CelPurManager.ClientID %>').prop('checked', true);
                            // $('#<%= chk_CelPurManager.ClientID %>').attr("checked", 'checked');
                            // $('#<%= chk_CelPurManager.ClientID %>').click();
                        }
                    }
                }
            }

            function clearData() {
                $('input[type="text"]').each(function () {
                    $(this).css({
                        "border": ""
                        //,"background": ""
                    });
                });

                $('#<%= txt_FirstName.ClientID %>').val("");
                $('#<%= txt_FirstName.ClientID %>').css({ "border": "" });
                $('#<%= lbl_FirstName.ClientID %>').val("");

                $('#<%= txt_LastName.ClientID %>').val("");
                $('#<%= txt_LastName.ClientID %>').css({ "border": "" });
                $('#<%= lbl_LastName.ClientID %>').val("");

                $('#<%= txt_Title.ClientID %>').val("");
                $('#<%= txt_Title.ClientID %>').css({ "border": "" });
                $('#<%= lbl_Title.ClientID %>').val("");

                $('#<%= txt_EMail.ClientID %>').val("");
                $('#<%= txt_EMail.ClientID %>').css({ "border": "" });
                $('#<%= lbl_EMail.ClientID %>').val("");

                $('#<%= txt_Pwd.ClientID %>').val("");
                $('#<%= txt_Pwd.ClientID %>').css({ "border": "" });
                $('#<%= lbl_Pwd.ClientID %>').val("");

                $('#<%= txt_SplPwd.ClientID %>').val("");
                $('#<%= txt_SplPwd.ClientID %>').css({ "border": "" });
                $('#<%= lbl_SplPwd.ClientID %>').val("");

                $('#<%= txt_ForgetQuest.ClientID %>').val("");
                $('#<%= txt_ForgetQuest.ClientID %>').css({ "border": "" });
                $('#<%= lbl_ForgetQuest.ClientID %>').val("");

                $('#<%= txt_ForgetQuestAns.ClientID %>').val("");
                $('#<%= txt_ForgetQuestAns.ClientID %>').css({ "border": "" });
                $('#<%= lbl_ForgetQuestAns.ClientID %>').val("");

                $('#<%= txt_PhoneNo.ClientID %>').val("");
                $('#<%= txt_PhoneNo.ClientID %>').css({ "border": "" });
                $('#<%= lbl_PhoneNo.ClientID %>').val("");

                $('#<%= txt_MobileNo.ClientID %>').val("");
                $('#<%= txt_MobileNo.ClientID %>').css({ "border": "" });
                $('#<%= lbl_MobileNo.ClientID %>').val("");

                $('#<%= txt_Notes.ClientID %>').val("");
                $('#<%= txt_Notes.ClientID %>').css({ "border": "" });
                $('#<%= lbl_Notes.ClientID %>').val("");

                $('#<%= chk_celesticaBuyer.ClientID %>').prop('checked', false);
                $('#<%= chk_CelPurManager.ClientID %>').prop('checked', false);
                $('#<%= chk_celesticaBuyer.ClientID %>').css("border", "''");
                $('#<%= chk_CelPurManager.ClientID %>').css("border", "''");

                $('#<%= ddl_BuyCode.ClientID %>').val("0");
                // $('#<%= chk_celesticaBuyer.ClientID %>').attr('checked', 'checked');
                // $('#<%= chk_celesticaBuyer.ClientID %>').removeAttr('checked');
            }

            $("#<%= btnSaveEdit.ClientID %>").click(function () {
                var res = false;
                res = chkvalidFields();
                if (res) {
                    saveOrUpdate("Update");
                    $('#<%= hidIsInsert.ClientID %>').val("");
                }
                return false;
            });

            $("#<%= btnSaveUsr.ClientID %>").click(function () {
                var res = false;
                res = chkvalidFields();
                if (res) {
                    saveOrUpdate("Insert");
                    $('#<%= hidIsInsert.ClientID %>').val("");
                }
                return false;
            });

            $("#<%= btnSaveSentEdit.ClientID %>").click(function () {
                var res = false;
                res = chkvalidFields();
                if (res) {
                    var rowid = jQuery("#datalist").jqGrid('getGridParam', 'selrow');
                    saveOrUpdate("Update");
                    var res = sendMail(rowid, '');
                    $('#<%= hidIsInsert.ClientID %>').val("");
                    fun_VESaveSentEdit();
                }
                return false;
            });

            $("#<%= btnSaveandSend.ClientID %>").click(function () {
                var res = false;
                res = chkvalidFields();
                if (res) {
                    var rowid = jQuery("#datalist").jqGrid('getGridParam', 'selrow');
                    saveOrUpdate("Insert");
                    var res = sendMail(rowid, '');
                    $('#<%= hidIsInsert.ClientID %>').val("");
                    fun_VESaveSentEdit();
                }
                return false;
            });

            $('#<%= txt_MobileNo.ClientID %>').blur(function () {
                var txtVal = $(this).val();
                var res = validatePhone(txtVal);
                //alert(res);
                if (res) {
                    $(this).css({ "border": "" });
                }
                else {
                    $(this).css({ "border": "1px solid red" });
                }
            });

            function validatePhone(txtPhone) {
                //var a = document.getElementById(txtPhone).value;
                var filter = /^[0-9-+]+$/;
                if (filter.test(txtPhone)) {
                    return true;
                }
                else {
                    return false;
                }
            }

            $('input[type="text"]').blur(function () {
                if ($.trim($(this).val()) != '') {
                    if (this.id == $('#<%= txt_EMail.ClientID %>').attr('id')) {
                        var emailRegex = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;

                        if (emailRegex.test($.trim($(this).val()))) {
                            var hidVal = $('#<%= hidIsInsert.ClientID %>').val();

                            if (hidVal != "" && (hidVal == 'Add' || hidVal == 'Insert' || hidVal == 'Update')) {
                                var eMailVal = $.trim($(this).val());
                                var isMailExist = chkEmailExist(this, eMailVal);
                            }
                            else {
                                $(this).css({
                                    "border": ""
                                });
                            }
                        }
                        else {
                            $(this).css({
                                "border": "1px solid red"
                            });
                        }
                    }
                    else {
                        $(this).css({
                            "border": ""
                        });
                    }
                }
                else {
                    if (this.id != $('#<%= txt_Notes.ClientID %>').attr('id')
                        && this.id != $('#<%= txt_PhoneNo.ClientID %>').attr('id') && this.id != $('#<%= txt_MobileNo.ClientID %>').attr('id')) {
                        $(this).css({
                            "border": "1px solid red"
                        });
                    }
                    else {
                        $(this).css({
                            "border": ""
                        });
                    }
                }
            });

            $('input[type="password"]').blur(function () {
                if ($.trim($(this).val()) != '') {
                    var res = Password_Mand(this);
                    if (res || res == undefined) {
                        $(this).css({
                            "border": ""
                        });
                    }
                    else {
                        $(this).css({
                            "border": "1px solid red"
                        });
                    }
                }
                else {
                    $(this).css({
                        "border": "1px solid red"
                    });
                }

            });

            function chkvalidFields() {
                var isValid = true;
                $('input[type="text"]').each(function () {
                    if ($.trim($(this).val()) == '' && this.id != $('#<%= txt_Notes.ClientID %>').attr('id')
                        && this.id != $('#<%= txt_PhoneNo.ClientID %>').attr('id') && this.id != $('#<%= txt_MobileNo.ClientID %>').attr('id') && this.id != "" && this.id != $('#<%= textboxmail.ClientID %>').attr('id')) {
                        var a = $.trim($(this).val());
                        var b = this.id;
                        isValid = false;
                        $(this).css({
                            "border": "1px solid red"
                            //,"background": "#FFCECE"
                        });
                    }
                    else {
                        if (this.id == $('#<%= txt_EMail.ClientID %>').attr('id')) {
                            var emailRegex = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
                            if (emailRegex.test($.trim($(this).val()))) {

                                var hidVal = $('#<%= hidIsInsert.ClientID %>').val();

                                if (hidVal != "" && (hidVal == 'Add' || hidVal == 'Insert')) {
                                    var eMailVal = $.trim($(this).val());
                                    var isMailExist = chkEmailExist($('#<%= txt_EMail.ClientID %>'), eMailVal);
                                }
                                else {
                                    $(this).css({
                                        "border": ""
                                    });
                                }
                            }
                            else {
                                isValid = false;
                                $(this).css({
                                    "border": "1px solid red"
                                });
                            }
                        }
                        else {
                            $(this).css({
                                "border": ""
                            });
                        }
                    }
                });

                $('input[type="password"]').each(function () {
                    if ($.trim($(this).val()) == '') {
                        isValid = false;
                        $(this).css({
                            "border": "1px solid red"
                            //,"background": "#FFCECE"
                        });
                    }
                    else {
                        $(this).css({
                            "border": ""
                            //,"background": ""
                        });
                    }
                });

                // $('#<%= chk_celesticaBuyer.ClientID %>').prop('checked', false);
                // $('#<%= chk_CelPurManager.ClientID %>').prop('checked', false);
                // $('#<%= chk_celesticaBuyer.ClientID %>').attr('checked', 'checked');
                // $('#<%= chk_celesticaBuyer.ClientID %>').removeAttr('checked');

                if ($('#<%= chk_celesticaBuyer.ClientID %>').is(':checked') != true && $('#<%= chk_CelPurManager.ClientID %>').is(':checked') != true) {
                    isValid = false;

                    $('#<%= chk_celesticaBuyer.ClientID %>').css('outline-color', 'red');
                    $('#<%= chk_celesticaBuyer.ClientID %>').css('outline-style', 'solid');
                    $('#<%= chk_celesticaBuyer.ClientID %>').css('outline-width', 'thin');

                    $('#<%= chk_CelPurManager.ClientID %>').css('outline-color', 'red');
                    $('#<%= chk_CelPurManager.ClientID %>').css('outline-style', 'solid');
                    $('#<%= chk_CelPurManager.ClientID %>').css('outline-width', 'thin');

                }
                else {
                    $('#<%= chk_celesticaBuyer.ClientID %>').css("border", "");
                    $('#<%= chk_CelPurManager.ClientID %>').css("border", "");
                }

                if (isValid == false) {
                    // e.preventDefault();
                    return false;
                }
                else {
                    return true;
                }
            }

            function chkEmailExist(source, eMailVal) {
                var res = false;
                var hidVal = $('#<%= hidIsInsert.ClientID %>').val();
                if (hidVal != "" && (hidVal == 'Add' || hidVal == 'Insert' || hidVal == 'Update')) {
                    var res = $.ajax({
                        type: "POST",
                        url: "../WebServices/InternalUser.asmx/fun_ChkMailExistOnAdd",
                        data: JSON.stringify({ eMail: eMailVal }),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (response) {
                            var isMailExist = response.d;
                            if (isMailExist) {
                                $(source).css({
                                    "border": "1px solid red"
                                });
                                $('#<%= txt_EMail.ClientID %>').val("");
                                $('#<%= txt_EMail.ClientID %>').focus();
                                alert("Mail already exist");
                            }
                            else {
                                $(source).css({
                                    "border": ""
                                });
                            }
                        },
                        error: function (data, status, jqXHR) { alert("FAILED:" + status); }
                    });
                }
                else {
                    $(source).css({
                        "border": ""
                    });
                }
            }

            function saveOrUpdate(proc) {
                var rowid = jQuery("#datalist").jqGrid('getGridParam', 'selrow');
                var perLogin = "";
                var buyerCode = "";
                if ($('#<%= chk_celesticaBuyer.ClientID %>').is(':checked')) {
                    perLogin += "2";
                    buyerCode = $('#<%= ddl_BuyCode.ClientID %>').val();
                    if (buyerCode == "0" || parseInt(buyerCode) == 0) {
                        alert("Please choose VendorTrak - Celestica Buyer.");
                        $('#<%= ddl_BuyCode.ClientID %>').focus();
                        return false;
                    }
                }

                if ($('#<%= chk_CelPurManager.ClientID %>').is(':checked')) {
                    if (perLogin != "")
                        perLogin += ",3";
                    else
                        perLogin = "3";
                }

                //if (buyerCode != "")
                //    buyerCode = buyerCode.substring(0, (buyerCode.length - 1));

                // if (perLogin != "")
                //     perLogin = perLogin.substring(0, (perLogin.length - 1));

                $('#datalist').jqGrid('setGridParam', {
                    postData: {
                        Action: proc
                                , CLUM_Id: (proc == "Insert") ? "" : rowid
                                , CLUM_FirstName: $.trim($('#<%= txt_FirstName.ClientID %>').val())
                                , CLUM_LastName: $.trim($('#<%= txt_LastName.ClientID %>').val())
                                , CLUM_Title: $.trim($('#<%= txt_Title.ClientID %>').val())
                                , CLUM_email: $.trim($('#<%= txt_EMail.ClientID %>').val())
                                , CLUM_Password: $.trim($('#<%= txt_Pwd.ClientID %>').val())
                                , CLUM_SpecialPassword: $.trim($('#<%= txt_SplPwd.ClientID %>').val())
                                , CLUM_FrgtPwd_Ques: $.trim($('#<%= txt_ForgetQuest.ClientID %>').val())
                                , CLUM_FrgtPwd_Ans: $.trim($('#<%= txt_ForgetQuestAns.ClientID %>').val())
                                , CLUM_Phone: $.trim($('#<%= txt_PhoneNo.ClientID %>').val())
                                , CLUM_Mobile: $.trim($('#<%= txt_MobileNo.ClientID %>').val())
                                , CLUM_PermittedLogin: perLogin
                                , CLUM_BuyerCode: buyerCode
                                , CLUM_Notes: $.trim($('#<%= txt_Notes.ClientID %>').val())
                        //, oper: "edit"
                    }
                });

                $('#datalist').trigger('reloadGrid');
                fun_VESaveEdit();
            }
            $('#<%= btnSaveSent.ClientID %>').click(function () {
                var rowID = $('#<%= hid_RowId.ClientID %>').val();
                var ccto = $.trim($('#<%= textboxmail.ClientID %>').val());
                var res = sendMail(rowID, ccto);
                $('#<%= hid_RowId.ClientID %>').val('');
                SentMailPopUpClose();
                return false;
            });

            function sendMail(rowid, ccto) {
                var path = "../Ajax/IntlUserSendMail.aspx?id=" + rowid + "&cc=" + ccto;
                var res = $.ajax({
                    type: "POST",
                    url: path,
                    // contentType: "application/json; charset=utf-8",
                    // dataType: "json",
                    success: function (response) {
                        if (response != "Success")
                            alert("Mail sending failed");
                    },
                    error: function (data, status, jqXHR) { alert("FAILED:" + status); }
                });
            }
        });

        function fun_SendMailClick(source, rowID) {
            fun_SendMailShow();
            $('#<%= textboxmail.ClientID %>').val("");
             $('#<%= hid_RowId.ClientID %>').val('');
            $('#<%= hid_RowId.ClientID %>').val(rowID);
            var $td = $('#datalist').jqGrid('getRowData', rowID);
            var eMail = $.trim($td["CLUM_email"]);
            $('#<%= lbl_DefMailTo.ClientID %>').html(eMail);
            return false;
        }

    </script>

        
Inside the form tag add the given code

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <table style="width: 1258px; background-color: #fff" align="center">
                <tr>
                    <td>&nbsp;</td>
                </tr>
                <tr>
                    <td align="center">
                        <table style="width: 96%; background-color: #fff">
                            <%--<tr>
                        <td>
                            <asp:Button ID="btnAdd" runat="server" Text="Add" CssClass="button" OnClientClick="return addRow();" />&nbsp;&nbsp;
                            <asp:Button ID="btnEdit" runat="server" Text="Edit" CssClass="button" OnClientClick="return editRow();" />&nbsp;&nbsp;
                            <asp:Button ID="btnDelete" runat="server" Text="Delete" CssClass="button" OnClientClick="return delRow();" />
                        </td>
                    </tr>--%>
                            <tr>
                                <td>
                                    <table id="datalist" cellpadding="0" cellspacing="0"></table>
                                    <div id="pager1"></div>
                                </td>
                            </tr>
                            <tr>
                                <td>&nbsp;</td>
                            </tr>
                            <tr>
                                <td align="right">
                                    <asp:LinkButton ID="lnkViewUsers" runat="server" OnClientClick="return fun_UsersViewClick(this);">View Inactive users</asp:LinkButton>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>

            <div id="toPopupEdit" style="background-color: #e1e6ed; width: 60%; height: auto; top: 100px; left: 800px;">
                <div class="closeEdit" onclick="return fun_CloseViewOrEdit();"></div>
                <span class="ecs_tooltipEdit">Press Esc to close <span class="arrowEdit"></span></span>
                <div id="popup_contentEdit" style="width: auto;">
                    <!--your content start-->
                    <table width="100%" border="0" cellspacing="0" cellpadding="0">
                        <tr>
                            <td>
                                <table width="100%" border="0" cellspacing="0" cellpadding="0">
                                    <tr>
                                        <td colspan="6" class="tabletop">Add New User</td>
                                        <td class="tabletop1">Permitted Logins</td>
                                    </tr>
                                    <tr height="4">
                                        <td colspan="7"></td>
                                    </tr>
                                    <tr>
                                        <td width="19%" style="font-size: 12px; font-weight: bold;">First Name<font color="red">*</font></td>
                                        <td colspan="5">
                                            <asp:Label ID="lbl_FirstName" runat="server" Text="" CssClass=""></asp:Label>
                                            <asp:TextBox ID="txt_FirstName" runat="server" CssClass="textboxround" Text="" Style="display: none;" TabIndex="1"
                                                MaxLength="20"></asp:TextBox>
                                            <asp:RequiredFieldValidator ID="FNReqR" runat="server"
                                                ControlToValidate="txt_FirstName" Display="None" ErrorMessage="First Name is required.">
                                            </asp:RequiredFieldValidator>
                                            <ajaxToolkit:ValidatorCalloutExtender runat="Server" ID="FNReqV" 
                                                    TargetControlID="FNReqR" 
                                                    HighlightCssClass="validatorCalloutHighlight" />
                                        </td>
                                        <td style="font-size: 12px;">
                                            <asp:CheckBox ID="chk_celesticaBuyer" runat="server" Text="VendorTrak - Celestica Buyer" Style="" TabIndex="12"/>
                                            &nbsp;&nbsp;
                                            <asp:DropDownList ID="ddl_BuyCode" runat="server" onclick="return fun_ApplicableBuyerCodes();" TabIndex="13"></asp:DropDownList>
                                        </td>
                                    </tr>
                                    <tr height="4">
                                        <td colspan="7"></td>
                                    </tr>
                                    <tr>
                                        <td style="font-size: 12px; font-weight: bold;">Last Name<font color="red">*</font></td>
                                        <td colspan="6">
                                            <asp:Label ID="lbl_LastName" runat="server" Text=""></asp:Label>
                                            <asp:TextBox ID="txt_LastName" runat="server" CssClass="textboxround" Text="" Style="display: none;" TabIndex="2"
                                                MaxLength="20"></asp:TextBox>
                                            <asp:RequiredFieldValidator ID="LastNameR" runat="server"
                                                ControlToValidate="txt_LastName" Display="None" ErrorMessage="Last Name is required.">
                                            </asp:RequiredFieldValidator>
                                            <ajaxToolkit:ValidatorCalloutExtender runat="Server" ID="LastNameV" 
                                                    TargetControlID="LastNameR" 
                                                    HighlightCssClass="validatorCalloutHighlight" />
                                        </td>
                                        <%--<td width="37%" class="evenrow">
                                            <span class="linknewblackpopup">
                                                <asp:LinkButton ID="lnk_AssApplBuyerCodes" runat="server" CssClass="toChkBoxpopupEdit" OnClientClick="return fun_ApplicableBuyerCodes();" TabIndex="13">Assign Applicable Buyer Codes : A,C,D</asp:LinkButton>
                                            </span>
                                        </td>--%>
                                    </tr>
                                    <tr height="4">
                                        <td colspan="7"></td>
                                    </tr>
                                    <tr>
                                        <td style="font-size: 12px; font-weight: bold;">Title<font color="red">*</font></td>
                                        <td colspan="5">
                                            <asp:Label ID="lbl_Title" runat="server" Text=""></asp:Label>
                                            <asp:TextBox ID="txt_Title" runat="server" CssClass="textboxround" Text="" Style="display: none;" TabIndex="3"
                                                MaxLength="50"></asp:TextBox>
                                            <asp:RequiredFieldValidator ID="TitleR" runat="server"
                                                ControlToValidate="txt_Title" Display="None" ErrorMessage="Please Enter Title">
                                            </asp:RequiredFieldValidator>
                                            <ajaxToolkit:ValidatorCalloutExtender runat="Server" ID="TitleV" 
                                                    TargetControlID="TitleR" 
                                                    HighlightCssClass="validatorCalloutHighlight" />
                                        </td>
                                        <td style="font-size: 12px;">
                                            <asp:CheckBox ID="chk_CelPurManager" runat="server" Text="VendorTrak - Celestica Purchase Manager" TabIndex="14"/>
                                        </td>
                                    </tr>
                                    <tr height="4">
                                        <td colspan="7"></td>
                                    </tr>
                                    <tr>
                                        <td style="font-size: 12px; font-weight: bold;">email<font color="red">*</font></td>
                                        <td colspan="5">
                                            <asp:Label ID="lbl_EMail" runat="server" Text=""></asp:Label>
                                            <asp:TextBox ID="txt_EMail" runat="server" CssClass="textboxround" Text="" Style="display: none;" TabIndex="4"
                                                MaxLength="50"></asp:TextBox>
                                            <asp:RequiredFieldValidator ID="EMailReqR" runat="server"
                                                ControlToValidate="txt_EMail" Display="None" ErrorMessage="EMail is required.">
                                            </asp:RequiredFieldValidator>
                                            <ajaxToolkit:ValidatorCalloutExtender runat="Server" ID="EMailReqV" 
                                                    TargetControlID="EMailReqR" 
                                                    HighlightCssClass="validatorCalloutHighlight" />
                                            <asp:RegularExpressionValidator ID="EMailReqExp" runat="server" ControlToValidate="txt_EMail" ErrorMessage="Please Enter valid email id"
                                                Display="None" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
                                            <ajaxToolkit:ValidatorCalloutExtender runat="Server" ID="EMailReqExpV" 
                                                    TargetControlID="EMailReqExp" 
                                                    HighlightCssClass="validatorCalloutHighlight" />
                                        </td>
                                        <td>&nbsp;</td>
                                    </tr>
                                    <tr height="4">
                                        <td colspan="7"></td>
                                    </tr>
                                    <tr>
                                        <td style="font-size: 12px; font-weight: bold;">Password<font color="red">*</font></td>
                                        <td colspan="6">
                                            <asp:Label ID="lbl_Pwd" runat="server" Text=""></asp:Label>
                                            <asp:TextBox ID="txt_Pwd" runat="server" CssClass="textboxround" Text="" TextMode="Password" Style="display: none;" TabIndex="5"
                                                MaxLength="16"></asp:TextBox>
                                            <asp:RequiredFieldValidator ID="PwdR" runat="server"
                                                ControlToValidate="txt_Pwd" Display="None" ErrorMessage="Please Enter Password">
                                            </asp:RequiredFieldValidator>
                                            <ajaxToolkit:ValidatorCalloutExtender runat="Server" ID="PwdV" 
                                                    TargetControlID="PwdR" 
                                                    HighlightCssClass="validatorCalloutHighlight" />
                                        </td>
                                    </tr>
                                    <tr height="4">
                                        <td colspan="7"></td>
                                    </tr>
                                    <tr>
                                        <td style="font-size: 12px; font-weight: bold;">Special Password<font color="red">*</font></td>
                                        <td colspan="6">
                                            <asp:Label ID="lbl_SplPwd" runat="server" Text=""></asp:Label>
                                            <asp:TextBox ID="txt_SplPwd" runat="server" CssClass="textboxround" Text="" TextMode="Password" Style="display: none;" TabIndex="6"
                                                MaxLength="16"></asp:TextBox>
                                            <asp:RequiredFieldValidator ID="SPwdR" runat="server"
                                                ControlToValidate="txt_SplPwd" Display="None" ErrorMessage="Please Enter Special Password">
                                            </asp:RequiredFieldValidator>
                                            <ajaxToolkit:ValidatorCalloutExtender runat="Server" ID="SPwdV" 
                                                    TargetControlID="SPwdR" 
                                                    HighlightCssClass="validatorCalloutHighlight" />
                                        </td>
                                    </tr>
                                    <tr height="4">
                                        <td colspan="7"></td>
                                    </tr>
                                    <tr>
                                        <td style="font-size: 12px; font-weight: bold;">Forgot Password Question<font color="red">*</font></td>
                                        <td colspan="6">
                                            <asp:Label ID="lbl_ForgetQuest" runat="server" Text=""></asp:Label>
                                            <asp:TextBox ID="txt_ForgetQuest" runat="server" CssClass="textboxround" Text="" Style="display: none;" TabIndex="7" Width="320"
                                                MaxLength="100"></asp:TextBox>
                                            <asp:RequiredFieldValidator ID="FQuesR" runat="server"
                                                ControlToValidate="txt_ForgetQuest" Display="None" ErrorMessage="Please Enter Forget Password Question">
                                            </asp:RequiredFieldValidator>
                                            <ajaxToolkit:ValidatorCalloutExtender runat="Server" ID="FQuesV" 
                                                    TargetControlID="FQuesR" 
                                                    HighlightCssClass="validatorCalloutHighlight" />
                                        </td>
                                    </tr>
                                    <tr height="4">
                                        <td colspan="7"></td>
                                    </tr>
                                    <tr>
                                        <td style="font-size: 12px; font-weight: bold;">Forgot Password Answer<font color="red">*</font></td>
                                        <td colspan="6">
                                            <asp:Label ID="lbl_ForgetQuestAns" runat="server" Text=""></asp:Label>
                                            <asp:TextBox ID="txt_ForgetQuestAns" runat="server" CssClass="textboxround" Text="" Style="display: none;" TabIndex="8" Width="320"
                                                MaxLength="100"></asp:TextBox>
                                            <asp:RequiredFieldValidator ID="FAnsR" runat="server"
                                                ControlToValidate="txt_ForgetQuestAns" Display="None" ErrorMessage="Please Enter Forget Password Question">
                                            </asp:RequiredFieldValidator>
                                            <ajaxToolkit:ValidatorCalloutExtender runat="Server" ID="FAnsV" 
                                                    TargetControlID="FAnsR" 
                                                    HighlightCssClass="validatorCalloutHighlight" />
                                        </td>
                                    </tr>
                                    <tr height="4">
                                        <td colspan="7"></td>
                                    </tr>
                                    <tr>
                                        <td style="font-size: 12px; font-weight: bold;">Phone</td>
                                        <td colspan="6">
                                            <asp:Label ID="lbl_PhoneNo" runat="server" Text=""></asp:Label>
                                            <asp:TextBox ID="txt_PhoneNo" runat="server" CssClass="textboxround" Text="" Style="display: none;" TabIndex="9"
                                                MaxLength="15"></asp:TextBox>
                                        </td>
                                    </tr>
                                    <tr height="4">
                                        <td colspan="7"></td>
                                    </tr>
                                    <tr>
                                        <td style="font-size: 12px; font-weight: bold;">Mobile</td>
                                        <td colspan="6">
                                            <asp:Label ID="lbl_MobileNo" runat="server" Text=""></asp:Label>
                                            <asp:TextBox ID="txt_MobileNo" runat="server" CssClass="textboxround" Text="" Style="display: none;" TabIndex="10"
                                                MaxLength="15"></asp:TextBox>
                                            <%--<asp:RegularExpressionValidator runat="server" ID="PNRegR" 
                                                ControlToValidate="txt_MobileNo" 
                                                Display="None" 
                                                ValidationExpression="((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}" 
                                                ErrorMessage="<b>Invalid Field</b><br />Please enter a phone number in the format:<br />(###) ###-####" /> 
                                            <ajaxToolkit:ValidatorCalloutExtender runat="Server" ID="PNReqV" 
                                                TargetControlID="PNRegR" 
                                                HighlightCssClass="validatorCalloutHighlight" />--%>
                                        </td>
                                    </tr>
                                    <tr height="4">
                                        <td colspan="7"></td>
                                    </tr>
                                    <tr>
                                        <td colspan="7">&nbsp;</td>
                                    </tr>
                                    <tr>
                                        <td colspan="7">&nbsp;</td>
                                    </tr>
                                    <tr>
                                        <td colspan="7" style="font-size: 12px; font-weight: bold;">Notes</td>
                                    </tr>
                                    <tr>
                                        <td colspan="7">
                                            <asp:Label ID="lbl_Notes" runat="server" Text=""></asp:Label>
                                            <asp:TextBox ID="txt_Notes" runat="server" CssClass="textareaboxround" Text="" Style="display: none;" TabIndex="11"
                                                MaxLength="4000"></asp:TextBox>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="7">&nbsp;</td>
                                    </tr>
                                    <tr>
                                        <td align="center" colspan="7">
                                            <table border="0" cellpadding="0" cellspacing="0">
                                                <tr>
                                                    <td>
                                                        <asp:Button ID="btnSaveUsr" runat="server" Text="Save" Style="display: none;" TabIndex="15"/></td>
                                                    <td>
                                                        <asp:Button ID="btnSaveandSend" runat="server" Text="Save &amp; Send email" Style="display: none;" TabIndex="15"/></td>
                                                    <td>
                                                        <asp:Button ID="btnINUsrEdit" runat="server" Text="Edit" TabIndex="16"/></td>
                                                    <td>
                                                        <asp:Button ID="btnCancelEdit" runat="server" Text="Cancel" OnClientClick="return fun_VECancelClick();" TabIndex="17"/>
                                                    </td>
                                                    <td>
                                                        <asp:Button ID="btnSaveEdit" runat="server" Text="Update" Style="display: none;" TabIndex="18"/></td>
                                                    <td>
                                                        <asp:Button ID="btnSaveSentEdit" runat="server" Text="Update &amp; Send email" Style="display: none;" TabIndex="19"/>
                                                    </td>
                                                </tr>
                                            </table>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="7">&nbsp;</td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                    </table>
                </div>
                <!--your content end-->
            </div>
            <!--toPopup end-->
            <div class="loaderEdit"></div>
            <div id="backgroundPopupEdit"></div>

           <%-- <div id="toPopupChkBoxEdit" style="background-color: #e1e6ed; width: 27%; left: 60%;">
                <div class="closeChkBoxEdit" onclick="return fun_ApplicableBuyerCodesClose();"></div>
                <span class="ecs_tooltipChkBoxEdit">Press Esc to close <span class="arrowChkBoxEdit"></span></span>
                <div id="popup_contentChkBoxEdit" style="width: auto; ">
                    <!--your content start-->
                    <!--<div id="div1" style="border:10px solid #F4F400; width:400px; position:absolute; top:228px; left: 763px; visibility:hidden;">-->
                    <table width="100%" bgcolor="#e1e6ed">
                        <tr>
                            <td colspan="4">
                                <div style="height:300px;overflow:scroll;">
                                    <asp:CheckBoxList ID="chkbxl_BuyCode" runat="server" Height="300">
                                    </asp:CheckBoxList>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="4" height="8px"></td>
                        </tr>
                        <tr>
                            <td align="center" colspan="4">
                                <asp:Button ID="btnCancelChkBox" runat="server" Text="Cancel" OnClientClick="return fun_CancelChkBoxEdit();" />
                                <asp:Button ID="btnUpdateChkBox" runat="server" Text="Update" OnClientClick="return fun_UpdateChkBoxL();" />
                            </td>
                        </tr>

                        <tr>
                            <td colspan="4" height="8px"></td>
                        </tr>
                        <tr>
                            <td colspan="4">
                                <span class="style1">Note: The buyer codes shown above are dynamically generated based on availabe active codes in Syteline</span>
                            </td>
                        </tr>
                    </table>
                    <!--   </div>-->
                </div>
                <!--your content end-->
            </div>
            <!--toPopup end-->
            <div class="loaderChkBoxEdit"></div>
            <div id="backgroundPopupChkBoxEdit"></div>--%>

            <div id="toPopupSent" style="background-color: #e1e6ed; width: 33%; padding-left: 23px;">
                <div class="closeSent" onclick="return SentMailPopUpClose();"></div>
                <span class="ecs_tooltipSent">Press Esc to close <span class="arrowSent"></span></span>
                <div id="popup_contentSent" style="width: auto;">
                    <!--your content start-->
                    <!-- <div id="div1" style="position:absolute; visibility:hidden; border:5px solid #FFFF00; top:100px; width:450px; left:600px; ">-->
                    <table width="100%" border="0" cellspacing="0" cellpadding="0">
                        <tr>
                            <td align="left" colspan="4" style="font-size: 12px;">
                                email with access key will be sent to &nbsp;<asp:Label ID="lbl_DefMailTo" runat="server" Text=""></asp:Label>
                            </td>
                        </tr>
                        <tr>
                            <td align="center" colspan="4">&nbsp;</td>
                        </tr>
                        <tr>
                            <td align="left" colspan="4" style="font-size: 12px;">Optional - send CC mail to: (Enter multiple mail IDs separated by commas)</td>
                        </tr>
                        <tr>
                            <td align="center">&nbsp;</td>
                            <td align="center">&nbsp;</td>
                            <td align="right">&nbsp;</td>
                            <td align="right">&nbsp;</td>
                        </tr>
                        <tr>
                            <td align="left">
                                <asp:TextBox ID="textboxmail" runat="server" CssClass="textboxmail"></asp:TextBox>
                                <asp:RegularExpressionValidator runat="server" ID="SendEMailRegR" ControlToValidate="textboxmail" Display="None"
                                  ErrorMessage="<b>Please Enter Valid EMailID</b>" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" /> 
                                <ajaxToolkit:ValidatorCalloutExtender runat="Server" ID="SendEMailReqV" 
                                 TargetControlID="SendEMailRegR" HighlightCssClass="validatorCalloutHighlight" />
                            </td>
                        </tr>
                        <tr>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                        </tr>
                        <tr>
                            <td colspan="4" align="center">
                                <table width="50%" border="0" cellspacing="0" cellpadding="0">
                                    <tr>
                                        <td></td>
                                        <td align="center">
                                            <asp:Button ID="btnCancelSent" runat="server" Text="Cancel" OnClientClick="return SentMailPopUpClose();" />
                                        </td>
                                        <td align="left">
                                            <asp:Button ID="btnSaveSent" runat="server" Text="Send"/>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                        <tr>
                            <td>&nbsp;</td>
                        </tr>
                        
                    </table>
                </div>
                <!--your content end-->
            </div>
            <!--toPopup end-->
            <div class="loaderSent"></div>
            <div id="backgroundPopupSent"></div>
            <asp:HiddenField ID="hidUsersView" runat="server" />
            <asp:HiddenField ID="hidIsInsert" runat="server" />
            <asp:HiddenField ID="hid_RowId" runat="server" />
        </ContentTemplate>
    </asp:UpdatePanel>


Then,
  Step 1: Create a folder in your project in the name of "WebServices"
  Step 2: Add webservice file in the name of "InternalUser.asmx"
  Step 3: In Web service file .cs page add the following code

   [WebMethod]
   // [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public void fillInternaluser()
    {
        oBAL_GridHandler.ProcessRequest(Context);
    }

Step 4 : In Business Layer create a handler file in the name of  "BAL_GridHandler.cs"
Step 5 : Then Bind the following code

 using System;
using System.Collections.ObjectModel;
using System.Web;
using System.Web.Script.Serialization;
using DAL;
using EL;
using System.Collections.Generic;
using System.Data;

namespace BAL
{
    public class BAL_GridHandler : IHttpHandler
    {
        DAL_GridHandler oDAL_GridHandler = new DAL_GridHandler();
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;
            HttpResponse response = context.Response;

            var ss = "";
            if (request["Action"] == null)
                ss = request["oper"].ToString();
            else
                ss = request["Action"].ToString();

            var fil = request["filters"];
            string _search = request["_search"];
            string numberOfRows = request["rows"];
            string pageIndex = request["page"];
            string sortColumnName = request["sidx"];
            string sortOrderBy = request["sord"];
            string status = "";// request["status"];
                if(request["status"]==null)
                    status="ActiveUser";
                else
                    status=request["status"].ToString();

            int totalRecords;
            var iFlag = false;
            var _uid = 0;

            switch (ss)
            {
                case "Fill":
                    fillGrid(numberOfRows, pageIndex, sortColumnName, sortOrderBy, out totalRecords, response, status);
                    break;
                case "Insert":
                case "add":
                    //Add Code to Insert and return bool value
                    iFlag = (bool)InsertOrUpdateRecord(response, request, "Insert");
                    if (iFlag)
                        fillGrid(numberOfRows, pageIndex, sortColumnName, sortOrderBy, out totalRecords, response, status);
                    break;
                case "Update":
                case "edit":
                    iFlag = (bool)InsertOrUpdateRecord(response, request, "Update");
                    if (iFlag)
                        fillGrid(numberOfRows, pageIndex, sortColumnName, sortOrderBy, out totalRecords, response, status);
                    //Update Code to Insert and return bool value
                    break;
                case "Delete":
                case "del":
                    _uid = Convert.ToInt32(request["CLUM_Id"]);
                    iFlag = (bool)oDAL_GridHandler.DeleteRecord(_uid);
                    if (iFlag)
                        fillGrid(numberOfRows, pageIndex, sortColumnName, sortOrderBy, out totalRecords, response, status);
                    //Delete Code to Insert and return bool value
                    break;
                case "ActiveUser":
                case "InactiveUser":
                    fillGrid(numberOfRows, pageIndex, sortColumnName, sortOrderBy, out totalRecords, response, status);
                    break;
                case "Activate":
                case "Inactivate":
                    _uid = Convert.ToInt32(request["CLUM_Id"]);
                    iFlag = (bool)oDAL_GridHandler.ActiveOrInactiveUser(_uid);
                   // if (iFlag)
                   // {
                        fillGrid(numberOfRows, pageIndex, sortColumnName, sortOrderBy, out totalRecords, response, status);
                   // }
                    break;
            }

        }

        private void fillGrid(string numberOfRows, string pageIndex, string sortColumnName, string sortOrderBy, out int totalRecords, HttpResponse response, string status)
        {
            Collection<EL_InternalUser> users = oDAL_GridHandler.GetUsers(numberOfRows, pageIndex, sortColumnName, sortOrderBy, out totalRecords, status);
            string output = InternalUserGridResults(users, Convert.ToInt32(numberOfRows), Convert.ToInt32(pageIndex), Convert.ToInt32(totalRecords));
            response.Write(output);
        }

        private object InsertOrUpdateRecord(HttpResponse response,HttpRequest request,string proc)
        {
            Collection<EL_InternalUser> users = new Collection<EL_InternalUser>();
            EL_InternalUser inUser = new EL_InternalUser();
            if (proc.Equals("Update"))
            inUser.CIU_Id = Convert.ToInt32(request["CLUM_Id"]);

            inUser.CIU_FirstName = request["CLUM_FirstName"];
            inUser.CIU_LastName = request["CLUM_LastName"];
            inUser.CIU_Title = request["CLUM_Title"];
            inUser.CIU_Email = request["CLUM_email"];
            inUser.CIU_Phone = request["CLUM_Phone"];
            inUser.CIU_Mobile = request["CLUM_Mobile"];
            inUser.CIU_Password = request["CLUM_Password"];
            inUser.CIU_Sp_Pwd = request["CLUM_SpecialPassword"];
            inUser.CIU_FrgtPwd_Quest = request["CLUM_FrgtPwd_Ques"];
            inUser.CIU_FrgtPwd_Ans = request["CLUM_FrgtPwd_Ans"];
            inUser.CIU_PermitLogins = request["CLUM_PermittedLogin"];
            inUser.CIU_BuyerCode = request["CLUM_BuyerCode"];
            inUser.CIU_Notes = request["CLUM_Notes"];
            users.Add(inUser);

            var res = (bool)oDAL_GridHandler.InsertOrUpdateRecord(users,proc);
            return res;
        }

        private string InternalUserGridResults(Collection<EL_InternalUser> users, int numberOfRows, int pageIndex, int totalRecords)
        {
            JQGridResults result = new JQGridResults();
            List<VN_JQGridRow> rows = new List<VN_JQGridRow>();
            foreach (EL_InternalUser user in users)
            {
                VN_JQGridRow row = new VN_JQGridRow();
                row.id = Convert.ToInt32(user.CIU_Id);
                row.cell = new string[14];
                row.cell[0] = user.CIU_Id.ToString();
                row.cell[1] = user.CIU_FirstName;
                row.cell[2] = user.CIU_LastName;
                row.cell[3] = user.CIU_Title;
                row.cell[4] = user.CIU_Email;
                row.cell[5] = user.CIU_Password;
                row.cell[6] = user.CIU_Sp_Pwd;
                row.cell[7] = user.CIU_FrgtPwd_Quest;
                row.cell[8] = user.CIU_FrgtPwd_Ans;
                row.cell[9] = user.CIU_Phone;
                row.cell[10] = user.CIU_Mobile;
                row.cell[11] = user.CIU_PermitLogins;
                row.cell[12] = user.CIU_BuyerCode;
                row.cell[13] = user.CIU_Notes;
                rows.Add(row);
            }
            result.rows = rows.ToArray();
            result.page = pageIndex;
            result.total =Convert.ToInt32(Math.Ceiling(Convert.ToDouble(totalRecords) / Convert.ToDouble(numberOfRows)));
            result.records = totalRecords;
            return new JavaScriptSerializer().Serialize(result);
        }

        public bool IsReusable
        {
            // Return false in case your Managed Handler cannot be reused for another request.
            // Usually this would be false in case you have some state information preserved per request.
            get { return false; }
        }
    }
}

Step 6 : In Entity Layer create a file in the name of "EL_GridHandler.cs"
Step 7 : Then append the given code in that file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EL
{
    interface EL_GridHandler
    {
    }

    public struct JQGridResults
    {
        public int page;
        public int total;
        public int records;
        public VN_JQGridRow[] rows;

    }

    public struct VN_JQGridRow
    {
        public int id;
        public string[] cell;
    }

    [Serializable]
    public class EL_InternalUser
    {
        public int CIU_Id
        { get; set; }

        public string CIU_FirstName
        { get; set; }

        public string CIU_LastName
        { get; set; }

        public string CIU_Title
        { get; set; }

        public string CIU_Email
        { get; set; }

        public string CIU_Phone
        { get; set; }

        public string CIU_Mobile
        { get; set; }

        public string CIU_Password
        { get; set; }

        public string CIU_Sp_Pwd
        { get; set; }

        public string CIU_FrgtPwd_Quest
        { get; set; }

        public string CIU_FrgtPwd_Ans
        { get; set; }

        public string CIU_PermitLogins
        { get; set; }

        public string CIU_BuyerCode
        { get; set; }

        public string CIU_Notes
        { get; set; }

        public bool CIU_Status
        { get; set; }
    }

    [Serializable]
    public class EL_NewPOS
    {
        public string PH_PONo
        { get; set; }

        public DateTime PH_PODate
        { get; set; }

        public string PH_BuyerCode
        { get; set; }

        public string VM_VendCode
        { get; set; }

        public string VM_Name
        { get; set; }

        public string BI_BuyerName
        { get; set; }

    public string BD_BuyerName
        { get; set; }
        public int PH_AutoID
        { get; set; }
    }
}


Step 8 : Then in DAL add the file in the name of ""
Step 9 : Then paste the following code

using System;
using System.Collections.ObjectModel;
using System.Web;
using EL;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Data.SqlClient;
using System.Data;

namespace DAL
{
    public class DAL_GridHandler
    {
        public Collection<EL_InternalUser> GetUsers(string numberOfRows, string pageIndex, string sortColumnName, string sortOrderBy, out int totalRecords,string status)
        {
            Collection<EL_InternalUser> users = new Collection<EL_InternalUser>();

            SqlParameter[] parameter = new SqlParameter[6];

            parameter[0] = new SqlParameter("@PageIndex", SqlDbType.Int);
            parameter[0].Value = pageIndex;

            parameter[1] = new SqlParameter("@SortColumnName", SqlDbType.VarChar, 50);
            parameter[1].Value = sortColumnName;

            parameter[2] = new SqlParameter("@SortOrderBy", SqlDbType.VarChar, 4);
            parameter[2].Value = sortOrderBy;

            parameter[3] = new SqlParameter("@NumberOfRows", SqlDbType.Int);
            parameter[3].Value = numberOfRows;

            parameter[4] = new SqlParameter("@TotalRecords", SqlDbType.Int);
            totalRecords = 0;
            parameter[4].Value = totalRecords;
            parameter[4].Direction = ParameterDirection.Output;

            if (!string.IsNullOrEmpty(status))
            {
                parameter[5] = new SqlParameter("@UsersShow", SqlDbType.Bit);
                parameter[5].Value = (status.Equals("ActiveUser") ? true : false);
            }

            SqlDataReader dataReader = (SqlDataReader)DBHelper.ExcecuteQuery(true, "SP_CLVT_Raja_CelesticaIntlUsrGet", parameter, CommandType.ExecuteDataReader);

            EL_InternalUser user;
            using (dataReader)
            {
                while (dataReader.Read())
                {
                    user = new EL_InternalUser();
                    user.CIU_Id = Convert.ToInt32(dataReader["CLUM_Id"]);
                    user.CIU_FirstName = Convert.ToString(dataReader["CLUM_FirstName"]);
                    user.CIU_LastName = Convert.ToString(dataReader["CLUM_LastName"]);
                    user.CIU_Title = Convert.ToString(dataReader["CLUM_Title"]);
                    user.CIU_Email = Convert.ToString(dataReader["CLUM_email"]);
                    user.CIU_Phone = Convert.ToString(dataReader["CLUM_Phone"]);
                    user.CIU_Mobile = Convert.ToString(dataReader["CLUM_Mobile"]);
                    user.CIU_Password = Convert.ToString(dataReader["CLUM_Password"]);
                    user.CIU_Sp_Pwd = Convert.ToString(dataReader["CLUM_SpecialPassword"]);
                    user.CIU_FrgtPwd_Quest = Convert.ToString(dataReader["CLUM_FrgtPwd_Ques"]);
                    user.CIU_FrgtPwd_Ans = Convert.ToString(dataReader["CLUM_FrgtPwd_Ans"]);
                    user.CIU_PermitLogins = Convert.ToString(dataReader["CLUM_PermittedLogin"]);
                    user.CIU_BuyerCode = Convert.ToString(dataReader["CLUM_BuyerCode"]);
                    user.CIU_Notes = Convert.ToString(dataReader["CLUM_Notes"]);
                    users.Add(user);
                }
                dataReader.Close();
                dataReader.Dispose();
            }
                totalRecords =Convert.ToInt32(parameter[4].Value);
            return users;
        }

        public object InsertOrUpdateRecord(Collection<EL_InternalUser> users, string proc)
        {
            int count = 0;
            foreach (EL_InternalUser user in users)
            {
                SqlParameter[] parameter;
                if (proc.Equals("Update"))
                {
                    parameter = new SqlParameter[14];
                    parameter[13] = new SqlParameter("@CIU_Id", SqlDbType.SmallInt);
                    parameter[13].Value = user.CIU_Id;
                }
                else
                {
                    parameter = new SqlParameter[13];
                }

                parameter[0] = new SqlParameter("@CIU_FirstName", SqlDbType.VarChar,50);
                parameter[0].Value = user.CIU_FirstName;

                parameter[1] = new SqlParameter("@CIU_LastName", SqlDbType.VarChar, 50);
                parameter[1].Value = user.CIU_LastName;

                parameter[2] = new SqlParameter("@CIU_Title", SqlDbType.VarChar, 100);
                parameter[2].Value = user.CIU_Title;

                parameter[3] = new SqlParameter("@CIU_Email", SqlDbType.VarChar, 100);
                parameter[3].Value = user.CIU_Email;

                parameter[4] = new SqlParameter("@CIU_Password", SqlDbType.NVarChar,50);
                parameter[4].Value = user.CIU_Password;

                parameter[5] = new SqlParameter("@CIU_Sp_Pwd", SqlDbType.NVarChar,50);
                parameter[5].Value = user.CIU_Sp_Pwd;

                parameter[6] = new SqlParameter("@CIU_FrgtPwd_Quest", SqlDbType.VarChar,100);
                parameter[6].Value = user.CIU_FrgtPwd_Quest;

                parameter[7] = new SqlParameter("@CIU_FrgtPwd_Ans", SqlDbType.VarChar,50);
                parameter[7].Value = user.CIU_FrgtPwd_Ans;

                parameter[8] = new SqlParameter("@CIU_Phone", SqlDbType.VarChar,20);
                parameter[8].Value = user.CIU_Phone;

                parameter[9] = new SqlParameter("@CIU_Mobile", SqlDbType.VarChar,20);
                parameter[9].Value = user.CIU_Mobile;

                parameter[10] = new SqlParameter("@CIU_PermitLogins", SqlDbType.VarChar,50);
                parameter[10].Value = user.CIU_PermitLogins;

                parameter[11] = new SqlParameter("@CIU_BuyerCode", SqlDbType.VarChar,50);
                parameter[11].Value = user.CIU_BuyerCode;

                parameter[12] = new SqlParameter("@CIU_Notes", SqlDbType.VarChar,500);
                parameter[12].Value = user.CIU_Notes;

                //parameter[2] = new SqlParameter("@CIU_Status", SqlDbType.Bit);
               // parameter[2].Value = totalRecords;
                string qry = "";
                if (proc.Equals("Insert"))
                    qry = "SP_CLVT_SAT_CelesticaIntlUsrInsert";
                else
                    qry = "SP_CLVT_SAT_CelesticaIntlUsrUpdate";

                count = Convert.ToInt32(DBHelper.ExcecuteQuery(true, qry, parameter, CommandType.ExecuteNonQuery));
            }

            return (count > 0) ? true : false;
        }
       
        public object DeleteRecord(int UserID)
        {
            SqlParameter[] parameter=new SqlParameter[1];
                parameter[0] = new SqlParameter("@CIU_Id", SqlDbType.SmallInt);
                parameter[0].Value = UserID;
                var count = Convert.ToInt32(DBHelper.ExcecuteQuery(true, "SP_CLVT_SAT_CelesticaIntlUsrDelete", parameter, CommandType.ExecuteNonQuery));
                return (count > 0) ? true : false;
        }

        public bool ActiveOrInactiveUser(int _uid)
        {
            SqlParameter[] parameter = new SqlParameter[1];
            parameter[0] = new SqlParameter("@CIU_Id", SqlDbType.SmallInt);
            parameter[0].Value = _uid;
            var count = Convert.ToInt32(DBHelper.ExcecuteQuery(true, "SP_CLVT_Raja_ActOrInactUser", parameter, CommandType.ExecuteNonQuery));
            return (count > 0) ? true : false;
        }

        public object fun_ChkMailExistOnAdd(InternalUsr_EL oInternalUsr_EL)
        {
            SqlParameter[] parameter = new SqlParameter[1];

            parameter[0] = new SqlParameter("@CLUM_email", SqlDbType.VarChar,100);
            parameter[0].Value = oInternalUsr_EL.Email;

            var res =Convert.ToInt32(DBHelper.ExcecuteQuery(true, "SP_CLVT_CelAdmin_ChkMailExist", parameter, CommandType.ExecuteScalar));
            return (res >= 1) ? true : false;
        }
    }
}