我有一个带有-by示例的RichTextBox-这个文本:
"This is my Text"
现在我想通过示例“搜索”RichTextBox中的Text(String):
"Text"
现在应该在RichTextBox中选择/突出显示(每个文本)..
有类似的东西:
myRichTextBox.Select();
但是我必须设置一个StartPosition等等,但我想搜索String!
我怎么能这样做? (搜索了stackoverflow,没有找到类似的东西..)
答案 0 :(得分:2)
int start = 0;
int indexOfSearchText = 0;
private void btnFind_Click(object sender, EventArgs e)
{
int startindex = 0;
if(txtSearch.Text.Length > 0)
startindex = FindMyText(txtSearch.Text.Trim(), start, rtb.Text.Length);
// If string was found in the RichTextBox, highlight it
if (startindex >= 0)
{
// Set the highlight color as red
rtb.SelectionColor = Color.Red;
// Find the end index. End Index = number of characters in textbox
int endindex = txtSearch.Text.Length;
// Highlight the search string
rtb.Select(startindex, endindex);
// mark the start position after the position of
// last search string
start = startindex + endindex;
}
}
public int FindMyText(string txtToSearch, int searchStart, int searchEnd)
{
// Unselect the previously searched string
if (searchStart > 0 && searchEnd > 0 && indexOfSearchText >= 0)
{
rtb.Undo();
}
// Set the return value to -1 by default.
int retVal = -1;
// A valid starting index should be specified.
// if indexOfSearchText = -1, the end of search
if (searchStart >= 0 && indexOfSearchText >=0)
{
// A valid ending index
if (searchEnd > searchStart || searchEnd == -1)
{
// Find the position of search string in RichTextBox
indexOfSearchText = rtb.Find(txtToSearch, searchStart, searchEnd, RichTextBoxFinds.None);
// Determine whether the text was found in richTextBox1.
if (indexOfSearchText != -1)
{
// Return the index to the specified search text.
retVal = indexOfSearchText;
}
}
}
return retVal;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
start = 0;
indexOfSearchText = 0;
}
如果您不理解此代码,请查看本文... http://www.dotnetcurry.com/ShowArticle.aspx?ID=146
答案 1 :(得分:2)
您可以使用Find方法查找搜索文本的开始索引:
int indexToText = myRichTextBox.Find(searchText);
然后,您可以使用此索引和Select方法选择文本:
int endIndex = searchText.Length;
myRichTextBox.Select(indexToText , endIndex);
答案 2 :(得分:1)
您只能在文本框中选择一个。你想要的是突出显示找到的文本 你可以这样做:
myRichTextBox.Text.IndexOf
并找到最后找到的索引+ 1作为起始位置,找到要突出显示的文本的位置。答案 3 :(得分:0)
private void Txt_Search_Box_TT_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
FOFO:
int start =
RtfAll_Messages.Find(Txt_Search_Box_TT.Text, RtfAll_Messages.SelectionStart + 1,
RichTextBoxFinds.None);
if (start >= 0)
RtfAll_Messages.Select(start, Txt_Search_Box_TT.Text.Length);
else
{
start = 0;
RtfAll_Messages.SelectionStart = 0;
RtfAll_Messages.SelectionLength = 0;
}
}
}