2014-01-22 25 views
0

我有一个Windows窗体应用程序。其中有一种形式,其中约20 +文本框的,我想验证天气的价值是否为空。如果值为空而不是错误提供者,那么指向哪个文本框是罪魁祸首。否则将数据存储到数据库。在插入数据库之前检查文本框上的空值

我已经创建了一个名为“null2”的函数,并且在执行endexecutequery方法之前将它称为按钮单击。

这里是我的代码:

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"); 
     } 
+0

问题是什么? – Steve

+0

即使对于空值,它的数据也存储在数据库中...... –

+0

上面的代码并未显示如何将返回值作为null2函数的FALSE处理。如果你展示如何称这种方法 – Steve

回答

0

也许你有你的检查错误。如果控件文本为空(TextBox的文本属性不为null),则应发出警告,设置错误提供程序并返回从循环中退出的错误。否则,你最终的循环(即没有文本框为空),并返回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将简化代码很多

但是,此代码不会尝试存储在什么数据库,所以真正的问题是在调用此函数和代码如何处理返回从这里假

编辑在您的评论更改下面的代码到这个

代码210
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); 
    } 
} 

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

+0

史蒂夫:它不工作... 即使你提到的代码只能去赶上块... 这很奇怪 –

+0

回答更新。现在catch块显示异常消息。请报告它,以便我们可以更好地了解为什么你会得到异常 – Steve

+0

错误\t 3'System.Windows.Forms.TextBox'是一个'类型',但用作'变量'... 这又是很奇怪的.. 现在该怎么走? –

相关问题