Hi LILALA,
Refer the below code.
Code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
protected void Search(object sender, EventArgs e)
{
this.BindGrid();
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT ContactName, City, Country FROM Customers WHERE ContactName LIKE '%' + @Search + '%' OR City LIKE '%' + @Search + '%' OR Country LIKE '%' + @Search + '%'";
cmd.Connection = con;
cmd.Parameters.AddWithValue("@Search", txtSearch.Text.Trim());
DataTable dt = new DataTable();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
gvCustomers.DataSource = dt;
gvCustomers.DataBind();
}
}
}
}
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvCustomers.PageIndex = e.NewPageIndex;
this.BindGrid();
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].Text = Regex.Replace(e.Row.Cells[0].Text, txtSearch.Text.Trim(), delegate(Match match)
{
return string.Format("<span style = 'background-color:#D9EDF7'>{0}</span>", match.Value);
}, RegexOptions.IgnoreCase);
e.Row.Cells[1].Text = Regex.Replace(e.Row.Cells[1].Text, txtSearch.Text.Trim(), delegate(Match match)
{
return string.Format("<span style = 'background-color:#D9EDF7'>{0}</span>", match.Value);
}, RegexOptions.IgnoreCase);
e.Row.Cells[2].Text = Regex.Replace(e.Row.Cells[2].Text, txtSearch.Text.Trim(), delegate(Match match)
{
return string.Format("<span style = 'background-color:#D9EDF7'>{0}</span>", match.Value);
}, RegexOptions.IgnoreCase);
}
}
HTML
Search:
<asp:TextBox ID="txtSearch" runat="server" />
<asp:Button Text="Search" runat="server" OnClick="Search" />
<hr />
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" AllowPaging="true"
OnRowDataBound="OnRowDataBound" OnPageIndexChanging="OnPageIndexChanging">
<Columns>
<asp:BoundField HeaderStyle-Width="150px" DataField="ContactName" HeaderText="Contact Name"
ItemStyle-CssClass="ContactName" HtmlEncode="false" />
<asp:BoundField HeaderStyle-Width="150px" DataField="City" HeaderText="City" />
<asp:BoundField HeaderStyle-Width="150px" DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
Screenshot