Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select a particular line in textbox?

from1 pictureenter image description hereI have a two forms, 1 and 2. Form1 has one textbox and form2 has a textbox and button. I want to go to a specified line, meaning that when I enter the value of form2's textbox then my mouse cursor goes to form1's textbox.

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;
      }
  }
}
like image 701
j.s.banger Avatar asked Feb 27 '13 20:02

j.s.banger


Video Answer


1 Answers

The TextBox.GetFirstCharIndexFromLine method finds the index of the first character of a line. So your selection starts there. Then find the end of that line, which is Environment.NewLine or the end of the text. Since the line number is entered by the user you should use int.TryParse to handle invalid input.

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);
    }
}
like image 189
pescolino Avatar answered Oct 06 '22 01:10

pescolino