Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

c# - How can I check multiple textboxes if null or empty without a unique test for each?

I have about 20 text fields on a form that a user can fill out. I want to prompt the user to consider saving if they have anything typed into any of the text boxes. Right now the test for that is really long and messy:

if(string.IsNullOrEmpty(txtbxAfterPic.Text) || string.IsNullOrEmpty(txtbxBeforePic.Text) ||
            string.IsNullOrEmpty(splitContainer1.Panel2) ||...//many more tests

Is there a way I could use something like an Array of any, where the array is made of the text boxes and I check it that way? What other ways might be a very convenient way in which to see if any changes have been made since the program started?

One other thing I should mention is there is a date time picker. I don't know if I need to test around that as the datetimepicker will never be null or empty.

EDIT: I incorporated the answers into my program, but I can't seem to make it work correctly. I set up the tests as below and keep triggering the Application.Exit() call.

        //it starts out saying everything is empty
        bool allfieldsempty = true;

        foreach(Control c in this.Controls)
        {
            //checks if its a textbox, and if it is, is it null or empty
            if(this.Controls.OfType<TextBox>().Any(t => string.IsNullOrEmpty(t.Text)))
            {
                //this means soemthing was in a box
               allfieldsempty = false;
               break;
            }
        }

        if (allfieldsempty == false)
        {
            MessageBox.Show("Consider saving.");
        }
        else //this means nothings new in the form so we can close it
        {                
            Application.Exit();
        }

Why is it not finding any text in my text boxes based on the code above?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sure -- enumerate through your controls looking for text boxes:

foreach (Control c in this.Controls)
{
    if (c is TextBox)
    {
        TextBox textBox = c as TextBox;
        if (textBox.Text == string.Empty)
        {
            // Text box is empty.
            // You COULD store information about this textbox is it's tag.
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...