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




Reply With Quote
