55555,哥哥帮帮我!

mhq731694994 2008-12-25 06:07:24
我的问题很小白,就是实现richtextbox的查找功能

控件只有三个:一个按钮,一个richtextbox,一个Textbox

Textbox输入要查找的内容:例如baby,然后按那个按钮,然后richtextbox里的"baby"就变成红色。可是,我想了很久写出了这样一个代码:

private void button1_Click(object sender, EventArgs e)
{
char[] textc = textBox2.Text.ToCharArray();
char[] rtextc = richTextBox1.Text.ToCharArray(); //把两个文本框的内容变成数组;
for (int i = 0; i < rtextc.Length - textc.Length + 1; i++)
{int tempi = i;
int temp=0;
for (int j = 0; j < textc.Length; j++) //小循环是判断的模块;
{

if (textc[j] == rtextc[i])
{
temp++;
tempi++;

}

}
if (temp == textc.Length) //实现变色的模块
{
richTextBox1.SelectionStart = i;
richTextBox1.SelectionLength = textc.Length;
richTextBox1.SelectionColor = Color.CadetBlue;
}




}
}

哥哥,奇怪的就是,按Cril+F5运行了第一次是可以的,可是第二次就不行了,为什么这样的啊?不是每次运行都是重新开始的吗??
哥哥们有什么好的方法解决这个问题的可以告诉一下小弟我吗?

Thanks!O(∩_∩)O
...全文
106 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
mhq731694994 2008-12-26
  • 打赏
  • 举报
回复
哇哇,谢谢你们了,我慢慢看!
net5i 2008-12-25
  • 打赏
  • 举报
回复
调用我下面的函数即可:(注意先设置richTextBox1的HideSelection属性为false
private int FindNext(string szFindText, bool bMatchCase, bool bReverse)
{
if (szFindText == null)
return -1;

RichTextBoxFinds findOptions = RichTextBoxFinds.None;

int start = this.richTextBox1.SelectionStart;
int end = start;

if (bReverse)
{
if (start == 0)
return -1;
start = 0;
end = this.richTextBox1.SelectionStart;
findOptions |= RichTextBoxFinds.Reverse;
}
else
{
if (start == this.richTextBox1.TextLength)
return -1;
start += this.richTextBox1.SelectionLength;
end = this.richTextBox1.TextLength;
this.richTextBox1.SelectionStart = start;
}
this.richTextBox1.SelectionLength = 0;

if (bMatchCase)
{
findOptions |= RichTextBoxFinds.MatchCase;
}
return this.richTextBox1.Find(szFindText, start, end, findOptions);
}

private void button1_Click(object sender, EventArgs e)
{
int result = this.FindNext(this.textBox1.Text, 是否区分大小写, false);
if(result >= 0)
{
this.richTextBox1.SelectionColor = Color.Red; //把查到的字符设置为红色
}
}
注意:这里是从当前光标位置处开始查找的。
sanjin240 2008-12-25
  • 打赏
  • 举报
回复
to
,按Cril+F5运行了第一次是可以的,可是第二次就不行了

没有这个问题!
Sader_ 2008-12-25
  • 打赏
  • 举报
回复
也许变红色了就不是原来的字串的,所以不匹配.比如"#"!="#"
wonsoft 2008-12-25
  • 打赏
  • 举报
回复
用RichTextBox 类型的FindName方法试试呢

void Find(object sender, RoutedEventArgs e)
{
object wantedNode = stackPanel.FindName("dog");
if (wantedNode is TextBlock)
{
// Following executed if Text element was found.
TextBlock wantedChild = wantedNode as TextBlock;
wantedChild.Foreground = Brushes.Blue;
}
}
niitnanfeng 2008-12-25
  • 打赏
  • 举报
回复
男扮女装?

110,533

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧