Gridview search as you type with ajax

Here I am going to explain you how to make search on asp.net Gridview with ajax. Start  ajax enabled website project in Default.aspx . And take TextBox and gridview in update panel as given below. And make sure you have set TextBox property autopostback true.It is assumed that we have table with name employee in Sql Server with column empname.

 

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
        <div>
             <asp:UpdatePanel ID="UpdatePanel1" runat="server" updatemode="Conditional">
        <Triggers >
        <asp:AsyncPostBackTrigger ControlID="txt"    />
        </Triggers>
        <ContentTemplate>
    <asp:TextBox runat="server" ID="txt" AutoPostBack="true"   OnTextChanged="txt_TextChanged" ></asp:TextBox>
    <asp:GridView runat="server" ID="GridView1"></asp:GridView>
            </ContentTemplate>
        </asp:UpdatePanel>
        </div>
    </form>
</body>
</html>






Now we go on Default.aspx.cs  file, write following code







using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Web.Configuration;
public partial class _Default : System.Web.UI.Page
{
    SqlConnection objcon = new SqlConnection(System.Web.Configuration.WebConfigurationManager.AppSettings["strCon"]);
    protected void Page_Load(object sender, EventArgs e)
    {
        txt.Attributes.Add("onkeyup", "javascript:setTimeout('__doPostBack(\'txt\',\'\')', 0)");
    }
    protected void txt_TextChanged(object sender, EventArgs e)
    {
        if (txt.Text != "")
        {
            objcon.Open();
            SqlDataAdapter da = new SqlDataAdapter("SELECT * from employee where empname like '" + txt.Text + "%'", objcon);
            DataSet ds = new DataSet();
            da.Fill(ds);
            GridView1.DataSource = ds.Tables[0];
            GridView1.DataBind();
        }
    }
}

We want to make search in gridview as we type so in Page_load event we have added one attribute to TextBox onkeyup with __dopostback. Now as soon as we press key through ajax gridview shows search results.