Friday, March 18, 2011

Filter datagrid based on some condition

Hi,

Here is the code to filter or search the gridview based on some condition.Aspx page:

<%@ Page Language="C#" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Text box Search example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table border="1px solid">
            <tr>
                <td>
                    Enter product Name:
                </td>
                <td>
                    <asp:TextBox ID="txtProductName" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:Button ID="btnSearch" runat="server" Text="Search" />
                </td>
            </tr>
            <tr>
                <td colspan="3">
                    <asp:GridView ID="grvProducts" runat="server" AllowPaging="True" AutoGenerateColumns="False"
                        DataKeyNames="ProductID" DataSourceID="SqlDataSource1" ShowFooter="True">
                        <Columns>
                            <asp:BoundField DataField="ProductID" HeaderText="ProductID" 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>
                </td>
            </tr>
        </table>
        <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="txtProductName" DefaultValue="%" Name="ProductName"
                    PropertyName="Text" Type="String" />
            </SelectParameters>
        </asp:SqlDataSource>
    </div>
    </form>
</body>
</html>

No comments:

Post a Comment