I am using the winforms textbox with multiline option ON. I want to limit the number of lines that can be entered in it. User should not be able to enter lines more than that.
How can I achieve that?
I am using the winforms textbox with multiline option ON. I want to limit the number of lines that can be entered in it. User should not be able to enter lines more than that.
How can I achieve that?
You need to check for
txtbox.Lines.Length
You need to handle this for 2 scenarios: 1. User is typing in the textbox 2. User has pasted text in the textbox
User typing in textbox
You need to handle the key press event of the text box to prevent user from entering more lines when max lines are exceeded.
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;
}
}
I have tested the above code. It works as desired.
User pastes some text in the textbox
To prevent the user from pasting more than the max lines, you can code the text changed event handler:
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.");
}
}
OK. How about defining a instance variable "lastKnownGoodText" and doing something like this:
private void textBox_TextChanged (object sender, EventArgs e) {
if (textBox.Lines.Length > 10)
textBox.Text = lastKnownGoodText;
else
lastKnownGoodText = textBox.Text;
}
Depending on what you're trying to achieve, there is also the MaxLength property to set the number of characters you can enter in the textbox (since a line may have a variable length).
Limit to MAX_LINES with truncation for copy/paste.
private void textBox1_KeyDown( object sender, KeyEventArgs e )
{
if ( textBox1.Lines.Length >= MAX_LINES && e.KeyValue == '\r' )
e.Handled = true;
}
private void textBox1_TextChanged( object sender, EventArgs e )
{
if ( textBox1.Lines.Length > MAX_LINES )
{
string[] temp = new string[MAX_LINES];
for ( int i = 0; i < MAX_LINES; i++ )
{
temp[i] = textBox1.Lines[i];
}
textBox1.Lines = temp;
}
}