Hi, how do I limit the number of lines in a multiline textbox? I don't want to limit the characters, just the number of lines.
Printable View
Hi, how do I limit the number of lines in a multiline textbox? I don't want to limit the characters, just the number of lines.
Handle the KeyDown event and trap the Enter key. Count the number of lines currently in the control and if it's already at the maximum then set e.SuppressKeyPress to True.
Could I possibly get a code example of how this is done?
Thanks
VB Code:
Private Const MAX_LINE_COUNT As Integer = 10 'for example Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown If e.KeyCode = Keys.Enter Then e.SuppressKeyPress = (Me.TextBox1.Lines.Length >= MAX_LINE_COUNT) End If End Sub
That works so long as wordwrapping is disabled.
If you can find a way to get keyup's e.surpresskeypress to work properly (it's in the arg, just doesn't stop anything); there's a much cleaner way. Otherwise, this will work as long as the lines your textbox is displaying is greater or equal to the number of lines you're capping.VB Code:
Private Const MaxLines As Int32 = 3 Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged dim hold As TextBox = DirectCast(sender, TextBox) If hold.GetPositionFromCharIndex(hold.Text.Length - 1).Y > (MaxLines * hold.Font.Height) Then hold.Text = hold.Text.Remove(hold.Text.Length - 1) hold.SelectionStart = hold.Text.Length End If End Sub
Edit: changed a me.textbox1 to hold
Given that the KeyPress event is raised before the KeyUp event, there isn't anything to suppress. KeyDown and KeyUp both receive a KeyEventArgs object but the SuppressKeyPress was added specifically for the KeyDown event and is only useful for that event.
Also, you DEFINITELY don't want to have a Using block like that in your event handler. The purpose of a Using block is to ensure that the object referred to by the variable declared in the Using statement gets disposed at the end of the block. I very much doubt that you want to dispose a TextBox in its own TextChanged event handler.
Haha, I was just about to fix that. I forgot I didn't insantiate the object. :lol:Quote:
Also, you DEFINITELY don't want to have a Using block like that in your event handler. The purpose of a Using block is to ensure that the object referred to by the variable declared in the Using statement gets disposed at the end of the block. I very much doubt that you want to dispose a TextBox in its own TextChanged event handler.