Filter Column data in a gridview using ASP.net

steps :

1) Create the simple Web application (ASP.Net with c#).

gridviewfilter

2) put the open the page (default.aspx) and put the below code in to that.

  <div>
<asp:Panel ID="pnlDisplay" runat="server" BackColor="GradientInactiveCaption" BorderStyle="Solid" Font-Size="Larger" ForeColor="#E0E0E0" Width="701px"> <center>Filter In GridView </center> </asp:Panel>
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="UserID"
CellPadding="4" ForeColor="#333333" GridLines="None">
<Columns>
<asp:TemplateField HeaderText="UserID" InsertVisible="False" SortExpression="UserID">
<ItemTemplate>
<asp:Label ID="lblUserID" runat="server" Text='<%# Eval("UserID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserName" SortExpression="UserName">
<%--Create the header template and put the textbox ,button and requiredfieldvalidator --%>
                        <HeaderTemplate>
<table>
<tr>
<td colspan="2">
UserName
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
</div>
</td>
<td>
<asp:Button ID="btnUserNameSubmit" runat="server" Text="Find" OnClick="btnUserNameSubmit_Click" />
</td>
</tr>
</table>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblUserName" runat="server" Text='<%# Eval("UserName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Address1" SortExpression="Address1">
<HeaderTemplate>
<table>
<tr>
<td colspan="2">
Address1
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtAddress1" runat="server"></asp:TextBox>
</div>
</td>
<td>
<asp:Button ID="btnAddress1Submit" runat="server" Text="Find" OnClick="btnAddress1Submit_Click" />
</td>
</tr>
</table>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblAddress1" runat="server" Text='<%# Eval("Address1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="EmailAddress" SortExpression="EmailAddress">
<HeaderTemplate>
<table>
<tr>
<td colspan="2">
Email Address
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtEmailAddress" runat="server"></asp:TextBox>
</td>
<td>
<asp:Button ID="btnEmailAddressSubmit" runat="server" Text="Find" OnClick="btnEmailAddressSubmit_Click" />
</td>
</tr>
</table>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblEmailAddress" runat="server" Text='<%# Eval("EmailAddress") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#EFF3FB" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
<asp:Label ID="lblRecordNotFound" runat="server" BackColor="#FF8080" Text="Record Not Found"
Visible="False" Width="279px"></asp:Label></div>

3) Open The Code Behind File and on the page load event put the below code.

protected void Page_Load(object sender, EventArgs e)
{
//check whether page is postback or not
//if page is not postback at that time we bind the gridview
if (!Page.IsPostBack)
{
//here write connection string
string strsql = DBConnection.sqlstr;

//create object for sqlconnection
//add namespace using System.Data.SqlClient;
SqlConnection sqlcon = new SqlConnection(strsql);

//here i use the query
//create the object of sqlcommand
SqlCommand sqlcmd = new SqlCommand("select * from [User]", sqlcon);

//create sqldataadapter object and give the sqlcommand as parameter
SqlDataAdapter adp = new SqlDataAdapter(sqlcmd);
//declare the dataset
DataSet ds = new DataSet();
//fill dataset using fill method of SqlDataAdapter
adp.Fill(ds);

//bind the GridView1
GridView1.DataSource = ds.Tables[0];

GridView1.DataBind();
}
}

4) here i am done this code for only one field UserName and other do your own thanks for your efforts. on the click event of the btnUserNameSubmit put the below code or directly write the code.

/// <summary>
/// when Apply the filter for UserName
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnUserNameSubmit_Click(object sender, EventArgs e)
{
//here write connection string
string strsql = DBConnection.sqlstr;

//create object for sqlconnection
SqlConnection sqlcon = new SqlConnection(strsql);

//get the txtUserName value
//and cast that in to the TextBox
string str = ((TextBox)GridView1.HeaderRow.FindControl("txtUserName")).Text;

//here i use the query
//create the object of sqlcommand

SqlCommand sqlcmd = new SqlCommand("select * from [User] where UserName like '%" + str + "%'", sqlcon);

//create sqldataadapter object and give the sqlcommand as parameter
SqlDataAdapter adp = new SqlDataAdapter(sqlcmd);
//declare the dataset
DataSet ds = new DataSet();
//fill dataset using fill method of SqlDataAdapter
adp.Fill(ds);

if (ds.Tables[0].Rows.Count > 0)
{
lblRecordNotFound.Visible = false;
//bind the GridView1
GridView1.DataSource = ds.Tables[0];

GridView1.DataBind();
}
else
{
//display message record not found
lblRecordNotFound.Visible = true;
}
}

/// <summary>
/// when apply the filter for address
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnAddress1Submit_Click(object sender, EventArgs e)
{
//do your own
}
/// <summary>
/// when apply the filter for EmailAddress
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnEmailAddressSubmit_Click(object sender, EventArgs e)
{
//do your own
}

5) Database Table Information.

TableName : User

UserID int
UserName varchar(50)
Password varchar(50)
Address1 varchar(50)
EmailAddress varchar(50)

Thank you.

About these ads

17 comments

  1. Anindya Chatterjee · · Reply

    Its throwing error is —

    Both DataSource and DataSourceID are defined on ‘GridView1′. Remove one definition.

  2. sahil · · Reply

    Hello Sir,
    I m sahil attually sir can you tellme please how can i filter the column name in grid view,suppose if i select in column name customers then all the customers data will come.in short can you tellme how can i achive the column filter in gridview..so can you help me please

    Thanx
    sahil

  3. how to connection database

  4. Hi Amit,
    Its working fine.I know the coding for filter but I failed to put filter controls in datagrid.Your article was helped me.

    Thank you

  5. Sairam · · Reply

    Man Awesome… Long time i m searching for Filtering Data in Grid View using TextBox . i got ur code working perfect by changing for my program vb.net .. U rock man…

    Thanks a lot

  6. How do i connect the db and also i get errors like connection string is not initialized

  7. Im having difficulty with connection string please can you help me

  8. this is great .. this help me alot .. thanks

  9. Thnx dear for ur help

    can u plz tell me if edit and deleting is enabled , when i m searching data after i press edit or delete its not working properly its editing the data which is at index 1 plz help me

    Regards

  10. Sree durga · · Reply

    Thank you so much sir…
    your article has helped me alot….

  11. How will you handle paging and sorting? if you are databinding in codebehind you will have to handle that also….

  12. waoo this coding is really grt but plzz tell me the thing is there any way for hiding the gridview when page is loading means it is just text box and button and after writhing the name it shows only the searching name in the gridview

  13. its good

  14. Vignesh.k · · Reply

    Thanks Sir, Its Working well
    Without header , Any Filter option avaiable in Gridview control itself??

  15. In my code button event not going to fire why so?

  16. suraj javarata · · Reply

    If i have a gridview with 2000 records populated via dataset ds1 for 4 different departments.
    Now i want to filter the data of gridview without postback.
    How can it be done?

  17. Nabeel Khan · · Reply

    Thank You So Much Your Have Helped Me Lot I Was Not Able To Display Error If Records Was Not Found
    Thanks Once Again :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 528 other followers