Thursday, 6 December 2012

gridview linqdatasource filter C#

gridview linqdatasource filter

Step 1)  How to configure LINQDataSource and Bind it GridView please see this article

How to add linqdatasource in asp.net northwnd database C#/VB.NET 

 

Step 2) Add Label , TextBox and Button

    <form id="form1" runat="server">
    <div>
        SearchQuery<asp:TextBox ID="TextBox1" runat="server" Height="40px" Width="282px"></asp:TextBox><asp:Button ID="Button1" runat="server" Text="Search/Filter/Query" OnClick="Button1_Click" />        <asp:LinqDataSource ID="LinqDataSource1" runat="server" ContextTypeName="WebApplication1.NorthWndCustomersDataContext" EnableDelete="True" EnableInsert="True" EnableUpdate="True" EntityTypeName="" TableName="Customers">
        </asp:LinqDataSource>
        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="CustomerID" DataSourceID="LinqDataSource1">
            <Columns>
                <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowSelectButton="True" />
                <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" SortExpression="CustomerID" />
                <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
                <asp:BoundField DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName" />
                <asp:BoundField DataField="ContactTitle" HeaderText="ContactTitle" SortExpression="ContactTitle" />
                <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
                <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
                <asp:BoundField DataField="Region" HeaderText="Region" SortExpression="Region" />
                <asp:BoundField DataField="PostalCode" HeaderText="PostalCode" SortExpression="PostalCode" />
                <asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />
                <asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" />
                <asp:BoundField DataField="Fax" HeaderText="Fax" SortExpression="Fax" />
            </Columns>
            <EditRowStyle BackColor="Red" ForeColor="Yellow" />
            <SelectedRowStyle BackColor="#660033" ForeColor="White" />
        </asp:GridView>

    </div>
    </form>
 

Step 3) Searches/Filters/Queries LinqDataSource


        protected void Button1_Click(object sender, EventArgs e)
        {
           //Search/filter String is Empty display all records,otherwise filter based on searchString
           if(String.IsNullOrEmpty(TextBox1.Text)) return;

           LinqDataSource1.Where = "Region==\""+TextBox1.Text+"\"";
           GridView1.DataSourceID = LinqDataSource1.ID;
           GridView1.DataBind();
        }
Here is the Output