Click here to Skip to main content
16,021,285 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi, I have a gridview that is populated on page load. I added a search option and when user clicks button I want the matching row to be highlighted in gridview. The grid will only highlight the matching row. Below is my code but it doesn't highlight the matching row. Any suggestions?


Thanks

What I have tried:

C#
protected void Button1_Click(object sender, EventArgs e)
{
	string cs = "Data Source=DESKTOP-Q69PRF4;Initial Catalog=new;Integrated Security=True";
	SqlConnection con = new SqlConnection(cs);
	if (con.State == ConnectionState.Open)
	{
		con.Close();
	}

	string Query = "select * from Posst where StId='"+TextBox1.Text+"'";
	SqlCommand com = new SqlCommand(Query, con);
	SqlDataAdapter da = new SqlDataAdapter(com);
	DataSet ds = new DataSet();
	DataTable dt = new DataTable();
	da.SelectCommand = com;
	da.Fill(dt);
	GridView1.DataSource = dt;
}

protected void TextBox1_TextChanged(object sender, EventArgs e)
{
	DataView DV = new DataView(dt);
	DV.RowFilter = string.Format("StID", TextBox1.Text);
   GridView1.DataSource = DV;
}
Posted
Updated 19-Sep-17 2:10am
v3

1 solution

Put following code in OnRow databound event handler of gridview

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);
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900