hi guys I wanted to ask if you can find a better way of simplifying my code. I have an if condition for a registration form filled with of course many textboxes that is needed to get the details of a certain user, if a certain textbox is empty it will show a messagebox saying "Please fill up the missing details" if you leave a textbox blank.

Now my code is like this:

string x = textBox7.Text;
string y = textBox8.Text;

            if ((x == "") || (y == ""))
            {                
                MessageBox.Show("Please fill up all the required details.");
            }

I can say it's quite time consuming and not very wise to put up all the textboxes in the condition and name them with a certain string variable. Can anyone suggest a simpler way of getting my code done??? Thanks in advanced for those who will help. God Bless you all!

You can do something like this

private void textBox_Leave(object sender, EventArgs e) {
    TextBox tb = sender as TextBox;

    if (tb.Text.Trim() == String.Empty) {
        MessageBox.Show(String.Format("Please enter something in the {0} box", tb.Tag.ToString()));
        tb.Focus();
    }
}

Set the Tag property of each textbox to what you'd like to go into the {0} spot, and set the Leave event to this method for each TextBox.

commented: "Set the Tag property of each textbox to what you'd like to go into the {0} spot, and set the Leave event to this method for each TextBox." << I don't know how to do that, teach me please +2

You could use a background Timer that fires, say, every 500ms and checks if all textboxes are filled, if not, keep the "send" or "apply" button disabled.

You can call this function ValidateForm on OnClick event.

protected void btnSave(object sender, EventArgs e)
{
    if(ValidateForm)
    {
        //do something if user fill all required data
    }
    else
    {
        MessageBox.Show("Please fill up all the required details.");
    }
}

 private bool ValidateForm()
 {
    if(!String.IsNullOrEmpty(txtBox1.Text) &&
        !String.IsNullOrEmpty(txtBox2.Text) &&
        !String.IsNullOrEmpty(txtBox3.Text) &&
        !String.IsNullOrEmpty(txtBox4.Text))
            return true;
        else
            return false;       
}

Also you can use ReqieredFieldValidator to check requred data.

again guys here's my code:

  private void button1_Click(object sender, EventArgs e)
        {
            string x = textBox7.Text;
            string y = textBox8.Text;

            if ((x == "") || (y == ""))
            {                
                MessageBox.Show("Please fill up all the required details.");
            }
        }

, @momerath is your textbox_leave a button???
let's say I have four textboxes and they are all blank, their names are tb1,tb2,tb3, and tb4... how are you going to insert them in the code that you provided?

@momerath: "Set the Tag property of each textbox to what you'd like to go into the {0} spot, and set the Leave event to this method for each TextBox." << I don't know how to do that, teach me please

I don't know how to do that, teach me please

You would set that up in the constructor (or Form.Loaded event handler) with something like this:

textBox7.Tag = "First Name";
textBox7.Leave += textBox_Leave;
textBox8.Tag = "Last Name";
textBox8.Leave += textBox_Leave;
...

The Tag property simply holds any object. The Leave event is triggered whenever focus is taken away from the control (TextBox). This means any time the user navigates to another control, via the mouse or keyboard, the event is triggered. This will not implicitly check the conditions before any actions are performed however (such as a button click).

You can take a look at this article. It shows the built in validation logic for WinForms. You could handle the Validating event the same way you would handle the Leave event, but you could also call ValidateChilder() in the button Click event.

If you don't want to use that, you could setup a quick array in the constructor:

TextBox[] checkEmptyTB = new TextBox[] {textBox7, textBox8, ...};

Then iterate through them in the Button.Click handler:

bool empty = false;
foreach(TextBox tb in checkEmptyTB)
    if(tb.Text.Trim() == string.Empty)
    {
        empty = true;
        break;
    }
if(empty)
    MessageBox.Show("Please fill up all the required details.");
else
{
    ...
}

God Bless you all!

Isn't it a bit presumptuous to assume others believe in the same things you do?

@nmaillet well then why are you frustrated for that? why can't you just ignore that then? if you're an atheist so be it, you're just showing how afraid you are to be an atheist

textBox_Leave(object sender, EventArgs e)
is an event it occurs whenever a control is no longer an active control on a form

@nmaillet well then why are you frustrated for that? why can't you just ignore that then? if you're an atheist so be it, you're just showing how afraid you are to be an atheist

I would say I'm more annoyed than frustrated. The same type of annoyed I get around the holidays when I see people saying "Merry Christmas" to everyone in the stores, no matter what their religious background.

@nmaillet unfortunately you have to deal with it, not everyone thinks the way you do.. okay let's not start something in here.

somebody help me use this code by momerath. like for example I have a registration form with three textboxes, a user is reminded to "Fill Up all the textboxes" when he/she unintentionally leaves a textbox or more than one textbox blank and then clicks the register button.. here's momerath's code and message:

*****Momerath's message starts here *****

"You can do something like this"

 private void textBox_Leave(object sender, EventArgs e) 
    TextBox tb = sender as TextBox;
    if (tb.Text.Trim() == String.Empty) 
    MessageBox.Show(String.Format("Please enter something in the {0} box", tb.Tag.ToString()));
       tb.Focus();
       }
    }

"Set the Tag property of each textbox to what you'd like to go into the {0} spot, and set the Leave event to this method for each TextBox."

For every textbox you have tag property(select tb control and press F4) and there is Tag on the bottom set it to the name you want to display in messagebox(in this case) and then after that go to the event section and for the leave event of the selected textbox select the name of this method Momerath created.

Do the same for every textbox on your form.

@Michael27 how can textBox_Leave and textBox_Enter work when I click the register button?

No, the textbox_leave is subscribed to Leave event of the every textbox you decide, it doesn't need to be in the register click event.
i'll try to explain
In Visual studio when you select the textbox control then press F4(it will display the properties of the control) in there you'll find the Tag property. Next there(in the same properties window there is thunderbolt icon(that is for events) click on it and then find Leave event and in the combobox of select the name textBox_Leave, do that(the event thing) for every textbox on your form.

No, the textbox_leave is subscribed to Leave event of the every textbox you decide, it doesn't need to be in the register click event.

What good is validation logic that doesn't prevent the user from submitting information? It's better than nothing, but doesn't really do what most developers want, and it would seem this includes the OP.

HAve you tried to that, have you tried to submit an empty textbox that is subscribed to this method in question? If you have that, you won't be able to do anthing untill every textbox that is subscribed to this event is filled.

I understand what it does, it won't let the Click event fire since the Button cannot get focus. Now let me ask you this, how do you validate a TextBox that the user never selects?

EDIT: A bit of personal preference, but I believe this is poor design. First, I don't believe a message box should be shown for every single validation error; it can break workflow for business users and simply be annoying for consumers. That's a bit of a minor gripe, but there are some important issues as well. For instance, what happens if a user tries to tab their way down to a particular TextBox? Suddenly their stuck filling out another TextBox. This isn't really an issue for names, addresses etc. It does become an issue when you start introducing large fields like descriptions, comments, etc. This may not make much of a difference in this case (since I have no idea what the form data is); however, having a user friendly UI can be very important.

Im with nmaillet on this one, I would personally prefer to have the validation fire on button click. This would allow use of errorproviders locally to each textbox to state which is causing issue.

Also the suggestion of using the leave event forces the user to complete one textbox at a time. Once they select one they must enter valid data before advancing. As a user I would find this quite unprofessional and irritating. Specially when one couldn't remember, say a credit card number on an online shop, so went to fill everything else out first, oh no im locked into the number field.

Would be better practice not to force the user.

Also the suggestion of using the leave event forces the user to complete one textbox at a time. Once they select one they must enter valid data before advancing. As a user I would find this quite unprofessional and irritating. Specially when one couldn't remember, say a credit card number on an online shop, so went to fill everything else out first, oh no im locked into the number field.

Thank you. I just added a small spiel to my last post, but it looks like you already covered it.

Thank you. I just added a small spiel to my last post, but it looks like you already covered it.

;) just thought I'd add my pennies worth.

Also the suggestion of using the leave event forces the user to complete one textbox at a time.

You should force user to complete the mandatory textboxes, not every textbox must be subscribed to that method, only the important one. And yes i wouldn't use messagebox either but it was suggested in the code.

Yeah, but the point is: you should be forced to enter valid data before submitting a form, but not before changing fields. Also, like I mentioned before, this doesn't force users to enter valid data, unless they select the field...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.