asp.netgridview

How can I filter the rows of a gridview based on a value in a textbox?


I have a gridview which I am binding through code behind, I want to filter the gridview based on the value given by the user in textbox.

It would be great if I'll be able to filter the gridview without any postback.


Solution

  • you could run a filter expression

    <asp:sqldatasource id="articles" runat="server"
       connectionstring="<%$ ConnectionStrings:aspa %>" 
       selectcommand="SELECT title, url, added, updated FROM aspx_articles ORDER BY title" 
       filterexpression="title LIKE '%{0}%' or url LIKE '%{0}%'">
       <filterparameters>
          <asp:controlparameter controlid="searchBox" propertyname="Text" />
       </filterparameters>
    </asp:sqldatasource>
    

    or this way

    Do you have a TextBox outside the GridView, and when you enter data into it and press a button, the GirdView should be filter on that data?

    If so, make sure your select command can taka a parameter with the value you want to filter on. Add a ControlParameter to the SelectParameters colelction of the DataSource control (if you use a DataSource control).

    Here is an example that uses the Northwind database, maybe this will help you:

    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <asp:Button ID="Button1" runat="server" Text="Button" />
            <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
                DataKeyNames="ProductID" DataSourceID="SqlDataSource1" ShowFooter="True">
                <Columns>
                    <asp:CommandField ShowSelectButton="True" />
                    <asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False"
                        ReadOnly="True" SortExpression="ProductID" />
                    <asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
                    <asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock" SortExpression="UnitsInStock" />
                    <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" />
                </Columns>
            </asp:GridView>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
                SelectCommand="SELECT [ProductID], [ProductName], [UnitsInStock], [UnitPrice] FROM [Alphabetical list of products] WHERE ([ProductName] LIKE '%' + @ProductName + '%')">
                <SelectParameters>
                    <asp:ControlParameter ControlID="TextBox1" DefaultValue="%" Name="ProductName" PropertyName="Text"
                        Type="String" />
                </SelectParameters>
            </asp:SqlDataSource>
    

    codes found here http://forums.asp.net/p/1034014/2904713.aspx