日期:2014-05-18  浏览次数:20734 次

richtextbox问题
假如现在richtextbox有如下内容:
aaaaaaa
bbbbbb"bds"fsdf
ccccccc
ddddddddd

如何知道"bds"在richtextbox哪一行?
知道在哪一行后如后定位到这行,就是滚动滚动条到行号所在位置

------解决方案--------------------
你把RichTextBox的Text读出来,放到一个string变量a里去

再调用split方法,把换行符传进去,返回一个string数组b(每行放到数组的一个元素中),这样这个Text就被切成一行一行的。
然后你用一个foreach迭代这个数组,或者用for(int i=0;i<b.Length,i++),然后通过b[i].indexof("bds"),查找是否存在这个字符,如果存在那么i+1就是你的行位置。

不知道楼主听明白了么……
------解决方案--------------------
for(int i=0;i<richTextBox1.Lines.Length;i++)
{
if (richTextBox1.Lines[i].ToString().IndexOf("bds") >= 0)
{
MessageBox.Show(i.ToString());
return;
}
}
------解决方案--------------------
1.选中整行。
2.用RichTextBox.SelectionBackColor, RichTextBox.SelectionColor等属性来获取和修改选中文本的属性。
如下,结合前面的代码:
C# code

        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;//设置颜色