Question How do I check for a string length?

black zero

Well-known member
Joined
Jan 15, 2009
Messages
53
Programming Experience
Beginner
Here's my code:
VB.NET:
    Private Sub CmbLabour1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles CmbLabour1.KeyPress
        If Char.IsDigit(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False Then
            e.Handled = True
        End If

        Dim a As Integer = checkStringlength(CmbLabour1.Text)

    End Sub

VB.NET:
    Private Function checkStringlength(ByVal link As String) As Integer

        Dim TestString As String = link

        Dim TestLen As Integer = Len(TestString)

        Return TestLen
    End Function


a doesn't return CmbLabour1.Text length properly. :( Help....
 
String class has a Length property:
VB.NET:
Dim len As Integer = CmbLabour1.Text.Length
The Len function give same result, but I prefer using the OOP functionality of the data types and .Net library over the runtime functions.

What is the result you expect since Text length is not it?
 
^precisely!!!

D:

You read my mind perfectly. Anyway, let me try that 2nd poster's solution first. I'll let you know if bad thing happens again.
 
^precisely!!!
You read my mind perfectly. Anyway, let me try that 2nd poster's solution first. I'll let you know if bad thing happens again.
I case you meant me ...
John's solution will give the same "wrong" result. Basically because 2 (in the above example) ist the correct result. It is the correct result because while you are in the KeyPress handler the TextBox still contains "AB" and not "ABC" (otherwise setting .Handled to true wouldn't make much sense). So if you want to know what length the text will have AFTER KeyPress is handled, you simply ... add "1" ;)
(Only if .handled is not set to true of course, because in that case the char will never make it to the textbox)
 
Depending on the case you can use the TextChanged event instead.
 
Back
Top