Search code examples
vb.netwinformstextbox

Check for Data in a set of Textboxes


I am working on creating a project which allows the user to input user data including an address. The data from the address is taken in multiple textbox fields for Street, City, State, Zip Code, and any additional information (like Unit # etc).

Now I am trying to set up some error checking and some error tooltips to provide the user with information when they are trying to submit the form data. I need to set it up so that every field (except for information, that is optional) has data in it. EDIT: I can't believe I forgot to mention this. On the form, inputting address data is optional. However I am trying to set it up so that if any field has data, it tells the user they need to have data in all the fields.

Right now I had a huge if statement set up to check for input:

If (Not street.Text.Equals("") And (city.Text.Equals("") Or state.Text.Equals("") Or code.Text.Equals(""))) Or
   (Not city.Text.Equals("") And (street.Text.Equals("") Or state.Text.Equals("") Or code.Text.Equals(""))) Or
   (Not state.Text.Equals("") And (street.Text.Equals("") Or city.Text.Equals("") Or code.Text.Equals(""))) Or
   (Not code.Text.Equals("") And (street.Text.Equals("") Or city.Text.Equals("") Or state.Text.Equals(""))) Or
   (Not info.Text.Equals("") And (street.Text.Equals("") Or city.Text.Equals("") Or state.Text.Equals("") Or code.Text.Equals(""))) Then

My question is simple. Is there an easier way to do this than the above If statement? Personally the If statement just looks super messy for me and I am trying to figure out if there is a different way to go about this. The code works for what I need it to do, just wondering if there are different angles to approach this problem from.


Solution

  • If user compiles any of address fields, simply check if one of your mandatory field is empty.

    If (Not street.Text.Equals("") Or Not city.Text.Equals("") Or Not state.Text.Equals("") Or Not code.Text.Equals("") Or Not info.Text.Equals("")) Then
        If (street.Text.Equals("") Or city.Text.Equals("") Or state.Text.Equals("") Or code.Text.Equals("")) Then
            Msgbox("If you want to provide an address please compile street, city, state and ZIP code.")
        End If
    End If
    

    Please consider using OrElse instead of Or.

    Also consider using IsNullOrWhiteSpace instead of Equals.