infolink

Friday, 31 August 2012

Filter GridView in .Net - ASP.Net


This tutorial is about how to add filter in gridview  in asp.net. It is very simple.
First you bind the GridView with database. if you not know how to bind than check the following tutorial:
http://developerqueries.blogspot.com/2012/08/display-data-in-gridview-from-database.html
Now add the DropDownList and fill it with all alphabets.

DropDownList
DropDownList
After that add another GridView. And on the selected index changed event of the DropDownList write following code:

DataTable dt = new DataTable();
        dt.Columns.Add("ID");
        dt.Columns.Add("Name");
        dt.Columns.Add("Father");
        int count = 0;
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            if (GridView1.Rows[i].Cells[1].Text.StartsWith(DropDownList1.SelectedItem.Text.ToLower()))
            {
                DataRow dr = dt.NewRow();
                dr["ID"] = GridView1.Rows[i].Cells[0].Text;
                dr["Name"] = GridView1.Rows[i].Cells[1].Text;
                dr["Father"] = GridView1.Rows[i].Cells[2].Text;
                dt.Rows.Add(dr);
                count++;
            }
        }
        if (count == 0)
        {
            Response.Write("No Record Found.....!");
            GridView1.Visible = true;
            GridView2.Visible = false;
        }
        else
        {
            GridView1.Visible = false;
            GridView2.Visible = true;
            GridView2.DataSource = dt;
            GridView2.DataBind();
        }

Now run the project and select the item from the DropDownList.

Filterd Record
Filterd Record


Record not found
Record not found

1 comment: