Dot-Net

限制 .net 文本框中的行數

  • May 6, 2014

我正在使用帶有多行選項的 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.");
   }
}

引用自:https://stackoverflow.com/questions/1048425