拿論壇問題來練習
要根據輸入關鍵字,把 GridView 內容內的關鍵字變成紅色
using System.Data;
namespace HighlightContent
{
public partial class HighlightContent : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt = new DataTable("Demo");
dt.Columns.Add("Data", typeof(string));
dt.Rows.Add("SQL Server 2014");
dt.Rows.Add("SQL Server 2012");
dt.Rows.Add("SQL Server 2008 R2");
dt.Rows.Add("SQL Server 2008");
dt.Rows.Add("Windows Server 2012 R2");
dt.Rows.Add("Windows Server 2012");
dt.Rows.Add("Windows Server 2008 R2");
dt.Rows.Add("Windows Server 2008");
gvData.DataSource = dt;
gvData.DataBind();
txtKeyword.AutoPostBack = true;
}
}
protected void txtKeyword_TextChanged(object sender, EventArgs e)
{
string keyword = txtKeyword.Text;
if (string.IsNullOrEmpty(keyword)) return;
string highlight = "" + keyword + "";
foreach (GridViewRow row in gvData.Rows)
{
// 重覆輸入關鍵時,要先把之前的 HTML 拿掉
row.Cells[0].Text = splitHTML(row.Cells[0].Text).Replace(keyword, highlight);
}
}
public static string splitHTML(string html)
{
string split = html;
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"<[^>]*>");
split = regex.Replace(split, "");
return split;
}
}
}
沒有留言:
張貼留言