检查是否有任何文本框为空,并用值填充它

本文关键字:填充 是否 任何 文本 检查 | 更新日期: 2023-09-27 17:52:39

private void btnSaveInformation_Click(object sender, EventArgs e)
    {
        foreach (Control child in Controls)
        {
            if (child is TextBox)
            {
                TextBox tb = child as TextBox;
                if (string.IsNullOrEmpty(tb.Text))
                {
                    tb.Text = @"N/A";
                }
            }
        }
        //var bal = new StudentBal
        //{
        //    FirstName = txtFirstName.Text
        //};
        //bal.InsertStudent(bal);
    }

我想要实现的是让系统检查是否有空白复选框,我在表格中有很多,如果它是空白的,那么赋值为"N/a"。我的代码做错了什么?谢谢你。

检查是否有任何文本框为空,并用值填充它

文本框是否放置在面板或其他分组控件中?如果是这样,窗体的Controls集合将不包含对它们的引用;它们只包含直接子元素(也就是面板等)

如果它们包含在组控件或面板中,您可能希望这样做:

foreach (Control child in myGroupPanel.Controls)
{
    if (child is TextBox) { // your additional code here }
}

如果您想要一个更健壮的方法,下面显示了获取所有控件列表的不同方法:

如何获得父控件的所有子控件?

如何获得一个特定类型(按钮/文本框)的窗体窗体的所有子控件?

您可以使用child.GetType()在迭代控件组时获取控件的类型,然后将其与typeof(TextBox)进行比较,这将有助于您从控件集合中过滤textbox。试试这个:

foreach (Control child in Controls)
{
    if (child.GetType() == typeof(TextBox))
    {
        TextBox tb = (TextBox)child;
        if (string.IsNullOrEmpty(tb.Text))
        {
            tb.Text = @"N/A";
        }
    }
}

或者你可以像下面这样使用遍历过滤集合(假设Controls是一个控件集合):

foreach (Control child in Controls.OfType<TextBox>().ToList())
{
     TextBox tb = (TextBox)child;
     if (string.IsNullOrEmpty(tb.Text))
     {
         tb.Text = @"N/A";
     }
}

我看不出你的代码有什么问题。我怀疑你正在寻找的控件是嵌套控件。

我建议扁平化层次结构并获得所有(嵌套的)控件,然后寻找特定的类型。

static Func<Control, IEnumerable<Control>> GetControls =
        (control) => control
            .Controls
            .Cast<Control>().SelectMany(x => GetControls(x))
            .Concat(control.Controls.Cast<Control>());
现在您可以在代码中使用上面的委托,如下所示。
foreach (TextBox tb in  GetControls(this).OfType<TextBox>())
{
    if (string.IsNullOrEmpty(tb.Text))
    {
        tb.Text = @"N/A";
    }
}