Searching in the GridView Control
There was a post on ASP.NET forums where the user asked how to search inside the GridView control. I was managed to implement this feature although if you plan to use the following code then I would highly recommend that you refactor it as it lacks in performance. In my opinion since you are searching inside the GridView the whole procedure should be handled on the client side using JavaScript or VBScript. Anyhow the following code uses the server side button click event to parse the GridView and highlight the search fields.
protected void Button1_Click(object sender, EventArgs e)
{
string searchString = txtSearch.Text;
StringBuilder sb = new StringBuilder();
DataTable dt = new DataTable();
List<GridViewRow> rows = new List<GridViewRow>();
foreach (GridViewRow row in GridView1.Rows)
{
TableCellCollection cells = row.Cells;
foreach (TableCell cell in cells)
{
if (cell.Text.ToLower().StartsWith(searchString.ToLower()))
{
cell.BackColor = System.Drawing.Color.Yellow;
foreach (TableCell c in cells)
{
sb.Append(c.Text);
}
sb.Append("<BR>");
}
else
{
cell.BackColor = System.Drawing.Color.White;
}
}
}
Label1.BackColor = System.Drawing.Color.Yellow;
Label1.Text = sb.ToString();
}
The code above simply goes through the GridView row by row and cell by cell. And if it finds a string that starts with the searchString then it highlights it and append it in the StringBuilder object.