C# 在循环中一起验证所有控件

C# 在循环中一起验证所有控件,c#,.net,winforms,validation,loops,C#,.net,Winforms,Validation,Loops,我使用以下方法来验证Winform的每个GroupBox中TextBox和ComboBox中的用户输入 private bool ValidateControlsIn(GroupBox gb) { foreach (Control c in gb.Controls.Cast<Control>().OrderBy(c => c.TabIndex)) { if (c is TextBox || c is ComboBox) {

我使用以下方法来验证Winform的每个
GroupBox
TextBox
ComboBox
中的用户输入

private bool ValidateControlsIn(GroupBox gb)
{
    foreach (Control c in gb.Controls.Cast<Control>().OrderBy(c => c.TabIndex))
    {
        if (c is TextBox || c is ComboBox)
        {
            if (string.IsNullOrWhiteSpace(c.Text))
            {
                MessageBox.Show(string.Format("Empty field {0 }", c.Name.Substring(3)));
                c.Focus();
                return false;
            }
        }
    }
    return true;
}
private bool ValidateControlsIn(GroupBox gb)
{
foreach(gb.Controls.Cast().OrderBy(c=>c.TabIndex)中的控件c)
{
如果(c是文本框| | c是组合框)
{
if(string.IsNullOrWhiteSpace(c.Text))
{
Show(string.Format(“空字段{0}”,c.Name.Substring(3));
c、 焦点();
返回false;
}
}
}
返回true;
}
除了
组合框
文本框
,我还有
单选按钮
和1个复选框1也需要验证

因此,我一直试图在验证时也考虑到它们,但没有成功


是否可以在相同的方法/循环中也选中
单选按钮
复选框

if (c is TextBox || c is ComboBox)
{
      if (string.IsNullOrWhiteSpace(c.Text))
      {
            MessageBox.Show(string.Format("Empty field {0 }", c.Name.Substring(3)));
            c.Focus();
            return false;
      }
}
else if(c is RadioButton)
{
      // Logic
}
else if(c is CheckBox)
{
      // Logic
}
如果要实际将其作为目标,请将其转换为其类型:

RadioButton rdb = c as RadioButton;
CheckBox cb = c as CheckBox;
例如:

else if(c is RadioButton)
{
     RadioButton rd = c as RadioButton;
     if(rd != null)
     {
           if(!rd.Checked)
                // Do something
     }
}

回想起来,您实际上可以将C强制转换为RadioButton,因为您已经检查了它是否是一个:
RadioButton rd=(RadioButton)C
,然后跳过
rd!=空验证可以通过多种不同的方式执行。在提交自己编写验证方法之前,请考虑使用事件处理程序和方法。这些规定会减少您的工作量,并添加取消事件参数以停止离开/失去焦点的过程

如果您致力于使用自己的foreach并迭代控件,那么您就有了一个不错的想法,尽管在扩展它时看起来不太好

foreach (Control c in gb.Controls.Cast<Control>().OrderBy(c => c.TabIndex))
        {
            if (c is TextBox || c is ComboBox)
            {
                if (string.IsNullOrWhiteSpace(c.Text))
                {
                    MessageBox.Show(string.Format("Empty field {0 }", c.Name.Substring(3)));
                    c.Focus();
                    return false;
                }
            }
            else if (c is RadioButton)
            {
                //handle me
                return false;
            }
            else if (c is CheckBox)
            {
                //handle me
                return false;
            }
        }
        return true;
foreach(gb.Controls.Cast().OrderBy(c=>c.TabIndex)中的控件c)
{
如果(c是文本框| | c是组合框)
{
if(string.IsNullOrWhiteSpace(c.Text))
{
Show(string.Format(“空字段{0}”,c.Name.Substring(3));
c、 焦点();
返回false;
}
}
否则,如果(c是单选按钮)
{
//对付我
返回false;
}
else if(c为复选框)
{
//对付我
返回false;
}
}
返回true;
使用可用的验证/验证规定,您可以向每个控件类型或每个单独的控件添加自定义处理程序。这允许您保持方法定义更小、更模块化。以下面的例子为例

private void button1_Click(object sender, EventArgs e)
    {
        // fires validating events for all controls that are selectable.
        // other constraints are available.
        this.ValidateChildren(ValidationConstraints.Selectable);
    }


    /// <summary>
    /// Handles the validating for a single control or multiple controls.
    /// Depends on the registration.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="CancelEventArgs"/> instance containing the event data.</param>
    private void textBox1_Validating(object sender, CancelEventArgs e)
    {
        bool condition = true;
        if (!condition)
        {
            // remaining validation and leave stack will not be performed.
            e.Cancel = true;
        }
    }

    /// <summary>
    /// Handles post validation for a single control or multiple controls.
    /// Depends on the registration.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
    private void textBox1_Validated(object sender, EventArgs e)
    {
        // handle after validation logic here.
        // spray happy faces all over the world.
    }
private void按钮1\u单击(对象发送者,事件参数e)
{
//激发所有可选控件的验证事件。
//还有其他限制条件。
this.ValidateChildren(ValidationConstraints.selective);
}
/// 
///处理单个控件或多个控件的验证。
///取决于注册情况。
/// 
///事件的来源。
///包含事件数据的实例。
私有无效textBox1_验证(对象发送方,CancelEventArgs e)
{
布尔条件=真;
如果(!条件)
{
//剩余的验证和离开堆栈将不会执行。
e、 取消=真;
}
}
/// 
///处理单个控件或多个控件的后验证。
///取决于注册情况。
/// 
///事件的来源。
///包含事件数据的实例。
私有无效文本框1_已验证(对象发送方,事件参数e)
{
//在这里处理验证后逻辑。
//向全世界喷洒快乐的脸。
}

我希望这能为您的问题提供一个像样的答案,并为您提供一个外观和行为更简洁的替代方案。

您可以在文本框检查下方添加一个else if,然后验证这些文本框。您尝试了什么?为什么没有成功?@Matthijs,但问题是要检查哪个属性为空<代码>c.值
/
c.已检查
/??@DonBoitnott,我试图在
|
之后的第一个If块中加入新的条件,比如
c.value==false
等,并在
Else If
部分等中加入新的条件。@Chathuranga:见我的答案:)问题不在于表单中所有的
单选按钮/复选框都应该是
选中的。例如:如果我们有两个
单选按钮
,分别称为
男按钮
女按钮
,那么只应选中其中一个?如何解决此问题?将它们放在
GroupBox
控件中。或者使用
CheckedChangedevent
,如果a.Checked为true,则将b.Checked设置为false。