I 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;
}
}
}
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With