Search code examples
vb.nettextboxnull

Check if null VB.NET


having trouble working out why this won't check the textbox too as well as the selected color.
If I do not put a color it flags up the "please enter fields" message, however if I do select a color but do not put anything in the name textbox then it carries on and just outputs a blank string in the msgbox.

Code is:

 Dim newColor As Color
Dim userName As String
Dim notEnoughArguments As String = "Please fill out the fields"


'Click event for button
Private Sub enterBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles enterBtn.Click

    If (userName Is "") Then

        MsgBox(notEnoughArguments)

    ElseIf (userName Is "" And colorLtb.SelectedItem Is Nothing) Then

        MsgBox(notEnoughArguments)

    ElseIf (colorLtb.SelectedItem Is Nothing) Then

        MsgBox(notEnoughArguments)

    Else

        userName = txt1.Text
        Dim selectedColor As String = colorLtb.SelectedItem.ToString
        newColor = Color.FromName(selectedColor)
        Dim msgBoxText As String = "Hello " + txt1.Text + "." & vbCrLf + "Changing your color to " + selectedColor + "."
        MsgBox(msgBoxText)

        Me.BackColor = newColor

    End If


End Sub

Solution

  • For strings (like your textbox contents) use String.IsNullOrWhitespace as a test. Also you want both arguments, right? So a single statement should do:

    If String.IsNullOrEmpty(userName) OrElse colorLtb.SelectedItem Is Nothing Then
        MessageBox.Show(notEnoughArguments)
        Return
    End If
    

    The problem is that Dim userName As String means the variable has nothing at all and that is not the same as an empty string. I always declare strings and immediately set them to String.Empty to avoid null reference exceptions, but using String.IsNullOrEmpty is a clean and robust way to test the contents of a string variable.