Results 1 to 2 of 2

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

  1. #1

    Thread Starter
    Fanatic Member Peter Porter's Avatar
    Join Date
    Jul 2013
    Posts
    532

    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.

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,274

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

    Just note that, if the user places the caret anywhere but the end of the text and enters a character then the character that that code removes will not be the last one entered. That's one difference between your code and the use of MaxLength. If you wanted to prevent new characters being entered rather allowing it and then removing things, you could handle keyboard events and predict what the text would be based on the current text, character entered and caret position. I do something like that in my Numeric TextBox thread in the CodeBank. In that code, I detect a Paste operation and then determine whether the text after the paste would be valid or not.

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