Gridview search as you type with ajax

Here I am going to explain you how to make search on 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="">
<head runat="server">
    <title>Untitled Page</title>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
             <asp:UpdatePanel ID="UpdatePanel1" runat="server" updatemode="Conditional">
        <Triggers >
        <asp:AsyncPostBackTrigger ControlID="txt"    />
    <asp:TextBox runat="server" ID="txt" AutoPostBack="true"   OnTextChanged="txt_TextChanged" ></asp:TextBox>
    <asp:GridView runat="server" ID="GridView1"></asp:GridView>

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 != "")
            SqlDataAdapter da = new SqlDataAdapter("SELECT * from employee where empname like '" + txt.Text + "%'", objcon);
            DataSet ds = new DataSet();
            GridView1.DataSource = ds.Tables[0];

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.