假如现在richtextbox有如下内容:
aaaaaaa
bbbbbb"bds"fsdf
ccccccc
ddddddddd如何知道"bds"在richtextbox哪一行?
知道在哪一行后如后定位到这行,就是滚动滚动条到行号所在位置
aaaaaaa
bbbbbb"bds"fsdf
ccccccc
ddddddddd如何知道"bds"在richtextbox哪一行?
知道在哪一行后如后定位到这行,就是滚动滚动条到行号所在位置
然后你用一个foreach迭代这个数组,或者用for(int i=0;i<b.Length,i++),然后通过b[i].indexof("bds"),查找是否存在这个字符,如果存在那么i+1就是你的行位置。不知道楼主听明白了么……
然后用一个for循环,看看前面有多少个换行不就可以了
{
if (richTextBox1.Lines[i].ToString().IndexOf("bds") >= 0)
{
MessageBox.Show(i.ToString());
return;
}
}
2.用RichTextBox.Select()将当前光标制定到字符串出现的地方.
3.用RichTextBox.ScrollToCaret()滚动到当前光标即可.
如下代码,从richTextBox1中找到"cfg",并且滚到出现的地方。 private void button1_Click(object sender, EventArgs e)
{
//找到指定的字符串,其实位置
int index = this.richTextBox1.Find("cfg");
if (index != -1)
{
//找到,则通过Select函数将当前光标调整到该位置
this.richTextBox1.Select(index, 0);
//滚动到当前光标
this.richTextBox1.ScrollToCaret();
}
}
string[] rtftext = richTextBox1.Lines;
int index = 0;
int start=0;
for (int i = 0; i < rtftext.Length; i++)
{
string temp = rtftext[i];
if (temp.IndexOf("bds") > -1)
{
index = i;
start=temp.IndexOf("bds") ;
break;
}
}
for(int i=0;i<index;i++)
{
start+=rtftext[i].Length;
}
richTextBox1.Select(start, 3);
如果只是想选中这些数据,那直接用if(this.richTextBox1.Find("cfg")!=-1)
this.richTextBox1.SelectedText="cfg";
岂不是更加方便
{
if(rtb.lins[i].contains("bds"))
.....
}
string[] strings = this.richTextBox1.Text.Split('\n');
int i = 0;
foreach (string s in strings)
{
if (s.IndexOf("bds")>=0)
{
this.richTextBox1.Select(i, s.Length);
this.richTextBox1.ScrollToCaret();
this.richTextBox1.SelectionBackColor = Color.Blue;
this.richTextBox1.SelectionColor = Color.White;
break;
}
i += (s.Length + 1);
}
要取得行号,就用下面这个函数,给出字符位置,找到所在行的位置。
int line = this.richTextBox1.GetLineFromCharIndex(charindex);PS:直接用SelectedText是不会自动滚动到这个位置的。
2.用RichTextBox.SelectionBackColor, RichTextBox.SelectionColor等属性来获取和修改选中文本的属性。
如下,结合前面的代码: private void button1_Click(object sender, EventArgs e)
{
//找到指定的字符串,其实位置
int index = this.richTextBox1.Find("cfg");
if (index != -1)
{
//找到,则通过Select函数将当前光标调整到该位置
this.richTextBox1.Select(index, 3);
//滚动到当前光标
this.richTextBox1.ScrollToCaret();
//获取行号
int line = this.richTextBox1.GetLineFromCharIndex(index);
//选中指定行
this.richTextBox1.Select(this.richTextBox1.GetFirstCharIndexFromLine(line), this.richTextBox1.Lines[line].Length);
//设置背景颜色,前景色等
this.richTextBox1.SelectionBackColor = Color.Red;
this.richTextBox1.SelectionColor = Color.White;
}
}
要取得行号:
int line = this.richTextBox1.GetLineFromCharIndex(charindex); 滚到当前光标的位置
richTextBox1.ScrollToCaret(); 设置选中内容的背景色
this.richTextBox1.Select.this.richTextBox1.GetFirstCharIndexFromLineline),this.richTextBox1.Lines[line].Length);//选中区域
this.richTextBox1.SelectionBackColor = Color.Red;//设置颜色
//使RichTextBox的垂直滚动条一直位于底部
//-------------------------------------------------------
richTextBox_已经收到.Focus();
richTextBox_已经收到.ScrollToCaret();
//-------------------------------------------------------