Thursday, 4 June 2015

Jquery AutoComplete in asp.net using Webmethod

Here is the Script Code
function UserNameAutoComplete() { 
    $("#UserName").autocomplete
        ({
            source: function (request, response) {
                $.ajax
                    ({
                        url: "GSIRRegionConfigFSSCUserLsPg.aspx/GetADUsers",
                        data: "{ 'strADUser' : '" + $("#UserName").val() + "'}",
                        dataType: "json",
                        type: "POST",
                        async: true,
                        contentType: "application/json; charset=utf-8",
                        dataFilter: function (data) { return data; },
                        success: function (data) {
                            if (data.d.length == 0) {
                                $("#UserName").val('');
                            }
                            else {
                                $("#UserName").val();
                            }
                            response($.map(data.d, function (item) {
                                return {
                                    value: item
                                }
                            }));
                        },
                        failure: function (response) {
                            alert(response.d);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(textStatus);
                        }
                    });
            },
            select: function (event, ui) {
                varusrsplit = ui.item.value.split(",");
                document.getElementById('UserName').value = '';
                document.getElementById('UserName').value = varusrsplit[0];
                document.getElementById('UserID').value = varusrsplit[1];
                ui.item.value = ui.item.value.split(",")[0];
            },
            minLength: 3
        });

}
Here is the WebMethod
[WebMethod]
    public static List<string> GetADUsers(string strADUser)
    {
        string AutoCmpltVal = string.Empty;
        List<string> objList = new List<string>();
        string query = string.Format("Select distinct EmployeeName,UserAccount from AdmADUserMasterDetails where EmployeeName LIKE '%{0}%'", strADUser);

        using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["SQLConnectionString"]))
        {
            SqlCommand cmd = new SqlCommand(query, con);
            SqlDataReader dr;
            con.Open();
            dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                AutoCmpltVal = (string)dr["EmployeeName"] + "," + (string)dr["UserAccount"];
                objList.Add(AutoCmpltVal);
            }
            return objList;
        }
    }

Sunday, 4 January 2015

Bind data to jqgrid using WebMethod in asp.net

We need add following pre-defined jquery plugins and css files to web form.Compare to asp.net Gridview,Jquery grid performance is past and lightweight.
As well as add Newtonsoft.json.dll


Code in jqGridWebMethod.aspx   
    <script src="JQGridReq/grid.locale-en.js"></script>
    <script src="JQGridReq/jquery-1.9.0.min.js"></script>
    <link href="JQGridReq/jquery-ui-1.9.2.custom.css" rel="stylesheet" />
    <script src="JQGridReq/jquery.jqGrid.js"></script>
    <link href="JQGridReq/ui.jqgrid.css" rel="stylesheet" />
    <script type="text/javascript">

        $(document).ready(function () {
            $.ajax({
                type: "POST",
                contentType: "application/json",
                data: "{}",
                url: "jqGridWebMethod.aspx/getEmployee",
                dataType: "json",
                success: function (data) {
                    data = data.d;
                    $("#list").jqGrid({
                        datatype: "local",
                        colNames: ['IdentityNumber', 'FirstName', 'Email', 'SurName',
                        'Password', 'BirthDate', 'Gender'],
                        colModel: [
                           { name: 'IdentityNumber', index: 'IdentityNumber', width:100},
                           {name: 'FirstName', index: 'FirstName', width: 100},
                           {name: 'Email', index: 'Email', width: 100},
                           {name: 'SurName', index: 'SurName', width: 100},
                           { name: 'Password', index: 'Password', width: 100},
                           {name: 'BirthDate', index: 'BirthDate', width: 100},
                           {name: 'Gender', index: 'Gender', width: 80}
                        ],
                        data: JSON.parse(data),
                        caption: "Employee Data"
                    });
                }
            });
        });
<table id="list"></table>
Code in jqGridWebMethod.aspx.cs
[WebMethod]
 public static string getEmployee()

    {

        SqlConnection con = new SqlConnection("Data Source=SHANKAR\\SQLEXPRESS;Initial

        Catalog=SMPL;Persist Security Info=True;User ID=sa;Password=hits@123");

        SqlCommand cmd = new SqlCommand();

        cmd.CommandText = "SELECT
        IdentityNumber,FirstName,SurName,Email,[Password],BirthDate,Gender FROM   
        dbo.tbl_Registration";
        cmd.CommandType = CommandType.Text;
        cmd.Connection = con;
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        con.Close();
        DataSet ds = new DataSet();
        da.Fill(ds);
        return Newtonsoft.Json.JsonConvert.SerializeObject(ds.Tables[0]);
    }
Final output could be
 




Tuesday, 16 December 2014

Adding multiple colors to single cell content using j script in asp.net

Here i bind data to GridView from database
Default.aspx
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
            <Columns>
                <asp:TemplateField HeaderText="Customer">
                    <ItemTemplate>
                        <asp:Label runat="server" ID="lblCustomer" Text='<%# Eval("Customer") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="ContactName">
                    <ItemTemplate>
                        <asp:Label runat="server" ID="lblContactName" Text='<%# Eval("ContactName") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="ContactTitle">
                    <ItemTemplate>
                        <asp:Label runat="server" ID="lblContactTitle" Text='<%# Eval("ContactTitle") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

Code in Default.aspx.cs
SqlConnection con = new SqlConnection("Data Source=INHYDSPARSHIMON\\SQL2012;Initial Catalog=SMPL;User ID=sa;Password=******");
            SqlDataAdapter da = new SqlDataAdapter("Select Customer,ContactName,ContactTitle from tbl_Customer", con);
            DataSet ds = new DataSet();
            da.Fill(ds, "tbl");
            GridView1.DataSource = ds;
            GridView1.DataBind();

//Call javascript function in code behind
ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage", "getdata();", true); 

Sample.js
function getdata() {
    var obj = document.getElementById('GridView1_lblContactName_0').innerText;
    var slp = [];
    slp = obj.split(' ');
    slp[0].fontcolor("green");
    for (var i = 0; i < slp.length; i++) {
        document.getElementById('GridView1_lblContactName_0').innerHTML = slp[0].fontcolor("green");
        document.getElementById('GridView1_lblContactName_0').innerHTML += slp[1].fontcolor("red");
    }
}
Output