Tuesday, September 28, 2010

How to search a GridView on a key press event

Demo:

I am using asp.net UpdatePanel control to partial page update. As there is no keyup event for the asp.net TextBox control, I add an attribute to the control in the page load, which postbacks the update panel on the keyup event of the TextBox.
this.txtDepartment.Attributes.Add("onkeyup", 
    string.Format("javascript:__doPostBack('{0}','')"this.upnlGridView.ClientID));
 For selecting, I have used DataTable’s Select(...) method.
DataRow[] rows = this.DataTable.Select(string.Format("Department LIKE '%{0}%'"this.txtDepartment.Text));
Then to identify the update panel postback event I have used __EVENTTARGET parameter of the Request’s Form[...] collection. If the __EVENTTARGET is equal to update panel’s ClientID then perform search based on TextBox value.
string target = this.Request.Form["__EVENTTARGET"];
if (!string.IsNullOrEmpty(target) && target.Equals(this.upnlGridView.ClientID))
{
    if (!string.IsNullOrEmpty(this.txtDepartment.Text))
    {
        DataRow[] rows = this.DataTable.Select(
            string.Format("Department LIKE '%{0}%'"this.txtDepartment.Text));
        this.grvItems.DataSource = this.LoadData(rows);
        this.grvItems.DataBind();
    }
    else
    {
        this.grvItems.DataSource = this.DataTable;
        this.grvItems.DataBind();
    }
}
For the demonstration purposes I have constructed a DataTable, but certainly you may get data from the database. To keep the example simple I have not implemented the search and paging. I leave it up to you to add suitable code. And also if it take a while to update you can improve the user experience by adding UpdateProgress where you can place little spinning image.

Example:
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<html>
<head id="Head1" runat="server">
 <script runat="server">
        string[] departments = { "Development""Accounting", 
                                   "Sales""Marketting""Management""Human Resouces" };
        private DataTable DataTable
        {
            get { return (DataTable)Session["DataTable"]; }
            set { Session["DataTable"] = value; }
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!this.IsPostBack)
            {
                DataTable dt;
                if (this.DataTable == null)
                    dt = this.DataTable = this.LoadData();
                else dt = this.DataTable;
                this.grvItems.DataSource = dt;
                this.grvItems.DataBind();
                this.txtDepartment.Attributes.Add("onkeyup",
                    string.Format("javascript:__doPostBack('{0}','')"this.upnlGridView.ClientID));
            }
            else
            {
                string target = this.Request.Form["__EVENTTARGET"];
                if (!string.IsNullOrEmpty(target) && target.Equals(this.upnlGridView.ClientID))
                {
                    if (!string.IsNullOrEmpty(this.txtDepartment.Text))
                    {
                        DataRow[] rows = this.DataTable.Select(
                            string.Format("Department LIKE '%{0}%'"this.txtDepartment.Text));
                        this.grvItems.DataSource = this.LoadData(rows);
                        this.grvItems.DataBind();
                    }
                    else
                    {
                        this.grvItems.DataSource = this.DataTable;
                        this.grvItems.DataBind();
                    }
                }
            }
        }
        protected void PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
        }
        protected void Sorting(object sender, GridViewSortEventArgs e)
        {
        }
        private DataTable LoadData()
        {
            return this.LoadData(null);
        }
        private DataTable LoadData(DataRow[] rows)
        {
            DataTable dt = this.GetTable();
            if (rows == null)
            {
                ///
                /// To demonstrate I have loaded data table in the code
                /// You may load this data from database.
                ///
                Random r = new Random();
                for (int i = 0; i < 300; i++)
                    dt.Rows.Add(
                        string.Format("E{0:000}", i),
                        departments[r.Next(0, 5)],
                        "Employee" + i,
                        string.Format("07967781{0:000}", i),
                        string.Format("employee{0:000}@company.com", i));
            }
            else
                foreach (DataRow r in rows) dt.Rows.Add(r[0], r[1], r[2], r[3], r[4]);
            return dt;
        }
        private DataTable GetTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("EmpID"String.Empty.GetType());
            dt.Columns.Add("Department"String.Empty.GetType());
            dt.Columns.Add("Name"String.Empty.GetType());
            dt.Columns.Add("Phone"String.Empty.GetType());
            dt.Columns.Add("Email"String.Empty.GetType());
            return dt;
        }         
 </script>
</head>
<body>    
 <form id="form1" runat="server">
        <asp:ScriptManager runat="server" ID="PageScriptManager" />
        Search Department: 
        <asp:TextBox 
            runat="server" 
            ID="txtDepartment"                    
            AutoPostBack="true" />
        <asp:UpdatePanel runat="server" ID="upnlGridView">
            <ContentTemplate>
                <hr />
                <asp:GridView 
                    runat="server" 
                    ID="grvItems" 
                    AllowPaging="true" 
                    AllowSorting="true" 
                    OnSorting="Sorting" 
                    OnPageIndexChanging="PageIndexChanging" 
                    CellPadding="5">                
                </asp:GridView>
            </ContentTemplate>
        </asp:UpdatePanel>
 </form>
</body>
</html>

7 comments:

Jerie M said...

bisakah anda memberikan juga source code untuk sorting dan page index change?

Charith Shyam Gunasekara said...

?

christopher torres said...

Hi I'm trying to represent the visual basic code so but I get an error



If Not Page.IsPostBack Then
Dim dt As DataTable
dt = listarProductos("")
GridView1.DataSource = dt
GridView1.DataBind()

Me.txtBusqueda.Attributes.Add("onkeyup", String.Format("javascript:__doPostBack('{0}','')", Me.upnPrueba.ClientID))
Else
Dim target As String
target = Request.Form("_EVENTTARGET")

If Not IsNothing(target) And Not target = "" And target.Equals(Me.upnPrueba.ClientID) Then

If Not IsNothing(txtBusqueda.Text) Or Not txtBusqueda.Text = "" Then
Dim dt As DataTable
dt = listarProductos(txtBusqueda.Text.Trim)
GridView1.DataSource = dt
GridView1.DataBind()

End If
End If
End If

target = Request.Form("_EVENTTARGET")

is null help me please

christopher torres said...

thank you so much¡¡¡¡¡¡¡¡

christopher torres said...

hola una consulta espero que me puedas ayudar, todo funciona bien pero despues que hizo una nueva busqueda al hacer click en algun control o en alguna parte de la pagina se refresca toda la pagina como si hiciera un postback creo que es por usar el __EVENTTARGET, tienes alguna idea de como evitar eso porfavor¡¡

christopher torres said...

please in your example when you do a search and you click on any part of the blade generates a postback you can see it in your own example, I would like to know because it is, thanks

http://www.web-sphere.co.uk/web/websphere/examples/SearchGridViewOnKeyPress.aspx

Charith Shyam Gunasekara said...

It does listen to keyup event, not onblur event of the textbox. It searches on key up event and if you need search to happen on lost focurs event, you may use onblur event instead of onkeyup event

iPhone Launch Screen Sizes

iPhone Portrait iOS 8 Retina HT 5.5 = 1242 X 2208 Retna HD 4.7 = 750 X 1134 iPhone Landscape iOS 8 Retina HD 5.5  2208 X 1242 iPho...