使用C#搜索并突出显示gridview中的行 [英] Search and highlight rows in gridview using C#

查看:172
本文介绍了使用C#搜索并突出显示gridview中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在页面加载时填充的gridview。我添加了一个搜索选项,当用户点击按钮时,我想在gridview中突出显示匹配的行。网格仅突出显示匹配的行。下面是我的代码,但它没有突出显示匹配的行。有什么建议?





谢谢



我的尝试:



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:

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;
}

推荐答案

将以下代码放在gridview的OnRow数据绑定事件处理程序中



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);
    }
}


这篇关于使用C#搜索并突出显示gridview中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆