如果没有对每个文本框进行唯一测试,如何检查多个文本框是否为空或为空? [英] How can I check multiple textboxes if null or empty without a unique test for each?

查看:22
本文介绍了如果没有对每个文本框进行唯一测试,如何检查多个文本框是否为空或为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个用户可以填写的表单上有大约 20 个文本字段.如果用户在任何文本框中输入了任何内容,我想提示用户考虑保存.现在的测试真的很长而且很混乱:

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?

我应该提到的另一件事是有一个日期时间选择器.我不知道是否需要对此进行测试,因为 datetimepicker 永远不会为 null 或为空.

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.

我将答案合并到我的程序中,但我似乎无法使其正常工作.我设置了如下测试并不断触发 Application.Exit() 调用.

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?

推荐答案

当然 -- 枚举您的控件以查找文本框:

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.
        }
    }
}

这篇关于如果没有对每个文本框进行唯一测试,如何检查多个文本框是否为空或为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆