微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐