C#WinForm判断界面上多个TextBox控件的值是否为空

版权声明:add oil https://blog.csdn.net/dekesun/article/details/89164390

说明:当WinForm界面上面有多个控件需要判断是否为空,如果用if(){}else,难免有些繁琐。在参考了其他博主的资料以后,我这里也做了一些整理,以TextBox控件示例,如下。

  1. VS打开创建一个WinForm窗体程序
    在这里插入图片描述
  2. 添加TextBox输入框控件和Label标签控件,以及增加一个Button检查按钮用于测试,我直接使用真实项目中的场景作为示例
    在这里插入图片描述
  3. 设置TextBox控件的Name属性,并与Label标签的Name属性所对应,对应的关系可以自己约束好,不一定用我的这种方式,具体如下两个截图所示。为什么要这么使用呢?其实是为了在MessageBox提示的时候,可以通过Label标签的文本作为MessagBox的提示文本,来以增强用户体验。
    Label在这里插入图片描述在这里插入图片描述
  4. 在Button 按钮点击事件中增加代码
 		private void button1_Click(object sender, EventArgs e)
        {
            TextBoxCheckIsNull();
        }

        #region 判断groupBox1-TextBox是否为空
        private bool TextBoxCheckIsNull()
        {
            bool flag = true;
            foreach (Control control in this.groupBox1.Controls)
            {
                if (control is TextBox)
                {
                    if (string.IsNullOrEmpty((control as TextBox).Text))
                    {
                        string txt_name = ((control as TextBox).Name);
                        Label l = (Label)this.Controls.Find("lb_" + txt_name, true)[0];
                        MessageBox.Show("缺少参数 \"" + l.Text + "\" !", "注意");
                        flag = false;
                        break;
                    }
                }
            }
            return flag;
        }
        #endregion
  1. 效果截图
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/dekesun/article/details/89164390