Henry Water
Henry Water

Reputation: 51

searching gridview in asp.net C#

I am trying to look for a way to search a grid view in asp.net using C# programming language. I dont want the grid view to have paging enabled. I would like it to bring up the result of the input typed in. E.g. If i typed in 's', all records starting with s would only be visible.

I have looked up on some sites which have databind in the code.

GridView1.DataSource = dt;
GridView1.DataBind();

Do I need to have this? What does this do?

Can I please get some help with advice or links that can answer my question. Thank you.

Upvotes: 0

Views: 23688

Answers (2)

Kinjal Gohil
Kinjal Gohil

Reputation: 968

You can use "DataTable" javascript functionality for this problem. Please refer https://www.datatables.net/.

$(document).ready(function(){
    $('#GridView1').DataTable();
});

only set your table id here and it will automatically set pagination, sorting, filtering of your table.

Thanks

Upvotes: 1

VDWWD
VDWWD

Reputation: 35514

Here is a complete working example. You way want to tweak it a bit to suit your own needs. And as Murray Foxcroft pointed out you will find several DataBindings in this example to make things work.

    <asp:TextBox ID="searchBox" runat="server"></asp:TextBox>
    <asp:Button ID="searchButton" runat="server" Text="search" OnClick="searchButton_Click" />
    <asp:Button ID="reset" runat="server" Text="reset" OnClick="resetSearchButton_Click" />
    <br />
    <br />
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
        <Columns>
            <asp:BoundField DataField="field01" HeaderText="Column A" />
            <asp:BoundField DataField="field02" HeaderText="Column B" />
            <asp:BoundField DataField="field03" HeaderText="Column C" />
        </Columns>
    </asp:GridView>

And in code behind;

   protected void Page_Load(object sender, EventArgs e)
    {
        //to make sure the data isn't loaded in postback
        if (!Page.IsPostBack)
        {
            //use a datatable for storing all the data
            DataTable dt = new DataTable();
            string query = "SELECT * FROM myTable ORDER BY myColumn DESC";

            //wrapping in 'using' means the connection is closed an disposed when done
            using (SqlConnection connection = new SqlConnection("myConnectionString"))
            using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
            {
                try
                {
                    //fill the datatable with the contents from the database
                    adapter.Fill(dt);
                }
                catch
                {
                }
            }

            //save the datatable into a viewstate for later use
            ViewState["myViewState"] = dt;

            //bind the datasource to the gridview
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }

    protected void searchButton_Click(object sender, EventArgs e)
    {
        string searchTerm = searchBox.Text.ToLower();

        //check if the search input is at least 3 chars
        if (searchTerm.Length >= 3)
        {
            //always check if the viewstate exists before using it
            if (ViewState["myViewState"] == null)
                return;

            //cast the viewstate as a datatable
            DataTable dt = ViewState["myViewState"] as DataTable;

            //make a clone of the datatable
            DataTable dtNew = dt.Clone();

            //search the datatable for the correct fields
            foreach (DataRow row in dt.Rows)
            {
                //add your own columns to be searched here
                if (row["field01"].ToString().ToLower().Contains(searchTerm) || row["field02"].ToString().ToLower().Contains(searchTerm))
                {
                    //when found copy the row to the cloned table
                    dtNew.Rows.Add(row.ItemArray);
                }
            }

            //rebind the grid
            GridView1.DataSource = dtNew;
            GridView1.DataBind();
        }
    }


    protected void resetSearchButton_Click(object sender, EventArgs e)
    {
        //always check if the viewstate exists before using it
        if (ViewState["myViewState"] == null)
            return;

        //cast the viewstate as a datatable
        DataTable dt = ViewState["myViewState"] as DataTable;

        //rebind the grid
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

Note that this searching of GridViews is probably only efficient with little amounts of data. If you are talking about 1000+ rows it would be much better to search the source (database) and bind those to the grid.

Note 2: Searching GridView cells like this (Rows[0].Cells[1].Text) only works with BoundField columns, not TemplateField and AutoGenerated Columns.

Upvotes: 1

Related Questions