Results 1 to 2 of 2

Thread: Detects characters entered exceeds TextBox width, removing last character to fit

Threaded View

  1. #1

    Thread Starter
    Fanatic Member Peter Porter's Avatar
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    581

    Detects characters entered exceeds TextBox width, removing last character to fit

    The below code will ensure that characters entered into a textBox doesn't exceed it's width, removing the last character that does.

    I know under the TextBox properties you can preset the number of characters allowed, but maybe someone out there would like to allow as many characters possible within it's width.

    Code:
    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    
            ' Detects if the length of characters entered exceeds the Textbox width
            If TextRenderer.MeasureText(TextBox1.Text, TextBox1.Font).Width > TextBox1.Width Then
    
                ' Removes the last character that exceeded the width of the Textbox
                TextBox1.Text = TextBox1.Text.Remove(TextBox1.Text.Length - 1)
    
                ' MessageBox pop-up
                MessageBox.Show("Your entry was too long for the text box!" & vbCrLf & _
                                    vbCrLf & "The last character entered was removed.", "Woops!")
      
            Else
            End If
    
        End Sub
    Last edited by Peter Porter; Nov 1st, 2019 at 03:23 PM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width