在文本框中搜索并突出显示文本

时间:2012-12-09 16:39:20

标签: c#

我试图在我的程序中创建某种搜索功能,这只是突出显示在文本框中找到的所有关键字

关键字框位于t2.text上,文本来自bx2.text

首先,我从这里Highlight key words in a given search text

尝试了这种方法

正则表达式正在运行,但突出显示不是

这里有什么不对吗?

    private void searchs()
    {
        var spattern = t2.Text;

        foreach(var s in bx2.Text)
        {
            var zxc = s.ToString();
            if (System.Text.RegularExpressions.Regex.IsMatch(zxc, spattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
            {
               bx2.Text.Replace(bx2.Text, @"<span class=""search-highlight"">$0</span>");
            }
        }
    }

2 个答案:

答案 0 :(得分:1)

链接的问题使用HTML格式,您无法在常规文本框中使用。

您需要一个RichText框。在那里,您可以使用控件的方法和属性(不使用HTML)格式化文本。

或使用浏览器控件而不是文本框来使用HTML格式。

答案 1 :(得分:1)

private void findButton_Click(object sender, EventArgs e)
{
    int count = 0;
    string keyword = keywordTextbox.Text.Trim();//getting given searching string
    int startPosition = 0; //initializing starting position to search
    int endPosition = 0;
    int endArticle = articleRichTextbox.Text.Length;//finding total number of character into the article
    for (int i = 0; i<endArticle  ; i =startPosition )//creating a loop until ending the article
    {
        if (i == -1) //if the loop goes to end of the article then stop
        {
            break;
        }
        startPosition = articleRichTextbox.Find(keyword, startPosition, endArticle, RichTextBoxFinds.WholeWord);//using find method get the begining position when find the searching string
        if (startPosition >= 0)     //if match the string                                                         //if don't match the string then it  return -1
        {
            count++;//conunting the number of occuerence or match the search string
            articleRichTextbox.SelectionColor = Color.Blue;//coloring the matching string in the article
            endPosition = keywordTextbox.Text.Length;
            startPosition = startPosition + endPosition;//place the starting position at the next word of previously matching string to continue searching.

        }


    }

    if (count == 0)//if the givn search string don't match at any time
    {
        MessageBox.Show("No Match Found!!!");
    }

    numberofaccurTextbox.Text = count.ToString();//show the number of occurence into the text box
}