c# – 在文本框中选择一个特定的行?

我有两个表单,1和2. Form1有一个文本框,form2有一个文本框和按钮.我想转到指定的行,这意味着当我输入form2的文本框的值时,我的鼠标光标将转到form1的文本框.
private void button1_Click(object sender,EventArgs e)
{
  int line = Form1.ab;
  for (int i = 1; i < line; i++)
  {
      if (i == Convert.ToInt16( textBox1.Text))
      {
        // fr.textBox1 is a textBox form1 and 
        // textBox1.text is a textBox of the form1
        fr.textBox1.SelectionStart =
           int.Parse( textBox1.Text) ;
        fr.textBox1.ScrollToCaret();
        break;
      }
  }
}

解决方法

TextBox.GetFirstCharIndexFromLine方法查找行的第一个字符的索引.
所以你的选择从那里开始.然后找到该行的结尾,即Environment.NewLine或文本的结尾.
由于用户输入行号,您应该使用int.TryParse来处理无效输入.
private void button1_Click(object sender,EventArgs e)
{
    int lineNumber;
    if (!int.TryParse(textBox2.Text,out lineNumber) || lineNumber < 0)
    {
        textBox1.Select(0,0);
        return;
    }

    int position = textBox1.GetFirstCharIndexFromLine(lineNumber);
    if (position < 0)
    {
        // lineNumber is too big
        textBox1.Select(textBox1.Text.Length,0);
    }
    else
    {
        int lineEnd = textBox1.Text.IndexOf(Environment.NewLine,position);
        if (lineEnd < 0)
        {
            lineEnd = textBox1.Text.Length;
        }

        textBox1.Select(position,lineEnd - position);
    }
}

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...