Click here to Skip to main content
15,904,024 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Good day to all, I want to locate all empty TextBox and ComboBox in easy way. As you can see the image below if fields is empty they show message and red back color in which textbox or combobox is empty.

image-sample[^]

What I have tried:

I try and something wrong, thank to those who can fix this problem.

TextBox [] textBox = { textBox1, textBox2};
        ComboBox[] comboBox = { comboBox1, comboBox2 };

        foreach (TextBox txt in textBox)
        {
            if (string.IsNullOrEmpty(txt.Text))//if all textbox is empty
            {
                txt.BackColor = Color.Red;
                string message = "Required field empty.";
                string tittle = "Error";
                MessageBoxButtons button = MessageBoxButtons.OK;
                DialogResult result = MessageBox.Show(message, tittle, button, MessageBoxIcon.Error);
                break;

            }
            else if (!string.IsNullOrEmpty(txt.Text))//if not empty
            {

                txt.BackColor = Color.White;
                MessageBox.Show("task complete");
                break;
            }

        }
        return;
Posted
Comments
Pete O'Hanlon 12-May-24 5:50am    
Your image isn't set to share, so we can't see it.

1 solution

We can't see your picture, but ... that code doesn't do what you expect it to - the break command in a loop exits the loop immediately.
So your code exits the loop during the first time round because it the textbox is empty it executes a break, and if it isn't it also executes a break. So it only ever looks at the first textbox.
And your code doesn't look at any comboboxes at all!

Plus, this structure is silly:
if (string.IsNullOrEmpty(txt.Text))
{
    ...
}
else if (!string.IsNullOrEmpty(txt.Text))
{
    ...
}
As it's easier to read and has exactly the same effect as this:
if (string.IsNullOrEmpty(txt.Text))
{
    ...
}
else
{
    ...
}
If you want to check all the textboxes, removes the break from both sides.
If you want to exit after the first empty textbox, remove the break from the else condition code block.

And consider using string.IsNullOrWhitespace[^] instead of empty, or a space in a text box is counted as "not empty".
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900