Lines of a textbox

Yeap. You can control the length and number of lines of text entered into a textbox through it's KeyPress sub. Here's a sample of and address textbox that limits the lines to 3 using an array & the split method to break apart the entered returns. I also measured the string to include text wrapping in the 3 line limit for the last line.

Visual Basic:
    Private Sub txtAddress_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtAddress.KeyPress

        If AscW(e.KeyChar) = 8 Then 'backspace
            e.Handled = False
            Exit Sub
        End If

        If txtAddress.Text.IndexOf(System.Environment.NewLine) > 0 Then
            Dim address() As String = Split(txtAddress.Text, System.Environment.NewLine)

            If address.GetUpperBound(0) > 1 Then
                If address.GetUpperBound(0) >= 2 _
                And AscW(e.KeyChar) = 13 Then 'enter key
                    e.Handled = True
                Else
                    Dim g As Graphics = Me.CreateGraphics
                    If g.MeasureString(address(2), txtAddress.Font).Width >= txtAddress.Width Then
                        e.Handled = True
                    Else : e.Handled = False
                    End If
                    g.Dispose()
                End If
            End If
        End If
    End Sub
 
Back
Top