在插入数据库之前检查文本框上的空值

时间:2014-01-22 14:52:50

标签: c# .net winforms

我有一个Windows窗体应用程序。其中有一个表单,有大约20多个文本框,我想验证天气的值是否为空。如果值为null,则为错误提供者shoud指向哪个文本框是罪魁祸首。否则将数据存储到数据库中。

在执行endexecutequery方法之前,我创建了一个名为“null2”的函数,我正在调用它按钮。

这是我的代码:

    public bool null2 (Control control)
    {

        foreach (Control C in control.Controls)
        {
            if (C is TextBox)
            {
                TextBox textbox = C as TextBox;
                if (string.IsNullOrWhiteSpace(textbox.Text))
                {

                    return(false) ;
                }
                else
                {
                    MessageBox.Show("Not happening bro...");
                    errorProvider1.SetError(textbox, "Cannot be Empty");
                    return(false) ;
                }
            }
            else
            {
               return (false);
            }
        }
        return(true);

    }
按钮上的

单击此处

if (!null2(this))
          {
             // MessageBox.Show("Some empty values are present");
              try
              {
                  int resul = subcom.ExecuteNonQuery();
                  if (resul > 0)
                  {
                      MessageBox.Show("Entered Successfully");
                  }
              }
              catch
              {
                  MessageBox.Show("Some details missing");
              }
         }
         else
        {
            MessageBox.Show("Some empty values are present");
         }

1 个答案:

答案 0 :(得分:0)

可能你的支票错了。如果控件文本为空(TextBox的text属性永远不为null),则应发出警告,设置错误提供程序并从循环中返回false。否则你结束循环(意味着没有TextBox为空)并返回true

public bool null2 (Control control) 
{
    foreach (TextBox t in control.Controls.OfType<TextBox>())
    {
        if (string.IsNullOrWhiteSpace(t.Text))
        {
            MessageBox.Show("Not happening bro...");
            errorProvider1.SetError(t, "Cannot be Empty");
            return(false) ;
        }
    }
    return(true);
}

另请注意使用IEnumerable.OfType如何简化代码

但是,此代码不会尝试在数据库中存储任何内容,因此真正的问题在于调用此函数的代码以及该代码如何从此处理返回为false

编辑将以下评论中的代码更改为此

if (null2(this)) 
{ 
   // If null2 returns true, then execute the query, 
   // there is no need to add another message box for the 
   // empty condition, you have already said that in the null2 method
   try 
   { 
       int resul = subcom.ExecuteNonQuery(); 
       if (resul > 0) 
       { 
           MessageBox.Show("Entered Successfully"); 
       } 
   } 
   catch (Exception ex)
   { 
       MessageBox.Show(ex.Message); 
   }
}

请将您评论中的代码添加到上面的原始问题