j.s*_*ger 7 c# textbox winforms
我有两个表单,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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
pes*_*ino 10
该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);
}
}
Run Code Online (Sandbox Code Playgroud)