.netc#-4.0asp.net-dynamic-data

How to implement Search in Dynamic Data Site in .NET 4 with LINQ to SQL Classes


I just created a Default Dynamic Data Site. How Can I add search to it?


Solution

  • You can add search functionality by doing the following.

    Firstly add the UI to the List.aspx page with the following code

    <fieldset id="MultiSearchFieldSet" class="DD" runat="server" visible="False">
     <asp:TextBox ID="txbMultiColumnSearch" CssClass="DDTextBox" runat="server" />
        <asp:Button ID="btnMultiColumnSearchSubmit" CssClass="DDControl" runat="server" Text="Search"
            OnClick="btnMultiColumnSearch_Click" />
        <asp:Button ID="btnMultiColumnSearchClear" CssClass="DDControl" runat="server" Text="Clear"
            OnClick="btnMultiColumnSearch_Click" />
    </fieldset>
    

    Next, we want to add the code-behind for the Button, so on List.aspx.cs go down to

    protected void btnMultiColumnSearch_Click(object sender, EventArgs e)
            {
            }
    

    And change it to

     protected void btnMultiColumnSearch_Click(object sender, EventArgs e)
            {
                var button = (Button)sender;
                if (button.ID == btnMultiColumnSearchClear.ID)
                    txbMultiColumnSearch.Text = String.Empty;
                else
                    using (PhoneListDataContext Data = new PhoneListDataContext())
                    {
                        EmployeeNameString = txbMultiColumnSearch.Text;
                        var SearchResults = Data.Employees.Where
                           (Employee => (Employee.FirstName.Contains(EmployeeNameString) || (Employee.LastName.Contains(EmployeeNameString))));
    
    
                        GridView1.DataSourceID = ""; 
                        GridView1.DataSource = SearchResults;
                        GridView1.DataBind();
    
    
                    }
            }
    

    And finally, beacause we are only searching the "Employees" table, I want to filter the visibility of the search box only to the employee's table.

    So I add this code to List.aspx.cs in protected void Page_Load

     if (table.DisplayName == "Employees") { MultiSearchFieldSet.Visible = true; }     
                else
                { MultiSearchFieldSet.Visible = false; };
    

    And now the page is Searchable!