Filter Column data in a gridview using ASP.net

18 Apr

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

12 Responses to “Filter Column data in a gridview using ASP.net”

  1. Anindya Chatterjee February 20, 2009 at 11:50 am #

    Its throwing error is —

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

  2. sahil May 29, 2009 at 2:25 pm #

    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. ram October 26, 2009 at 6:43 am #

    how to connection database

  4. shanwaj November 12, 2009 at 6:25 am #

    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 May 13, 2010 at 5:43 am #

    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. Hari June 14, 2010 at 8:58 pm #

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

  7. Hari June 14, 2010 at 9:43 pm #

    Im having difficulty with connection string please can you help me

  8. sam July 8, 2010 at 8:01 am #

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

  9. Sarkash October 28, 2010 at 3:01 pm #

    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 November 29, 2010 at 4:27 am #

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

  11. Chris February 3, 2011 at 6:07 pm #

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

  12. Asad Ali February 22, 2011 at 2:40 pm #

    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

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 )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 275 other followers

%d bloggers like this: