我正在使用带有多行选项的 winforms 文本框。我想限制可以输入的行数。用户不能输入更多行。
我怎样才能做到这一点?
最佳答案
你需要检查
txtbox.Lines.Length
您需要针对 2 种情况处理此问题:1. 用户正在文本框中输入 2. 用户已将文本粘贴到文本框中
用户在文本框中输入
您需要处理文本框的按键事件,以防止用户在超过最大行数时输入更多行。
private const int MAX_LINES = 10;
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (this.textBox1.Lines.Length >= MAX_LINES && e.KeyChar == '\r')
{
e.Handled = true;
}
}
我已经测试了上面的代码。它按预期工作。
用户在文本框中粘贴一些文本
为防止用户粘贴超过最大行数,您可以编写文本更改事件处理程序:
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (this.textBox1.Lines.Length > MAX_LINES)
{
this.textBox1.Undo();
this.textBox1.ClearUndo();
MessageBox.Show("Only " + MAX_LINES + " lines are allowed.");
}
}
关于.net - 限制 .net 文本框中的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1048425/