【问题标题】:Check if any textbox is empty and fill it with a value检查任何文本框是否为空并用值填充
【发布时间】:2016-06-28 02:49:45
【问题描述】:
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”。我的代码做错了什么?谢谢。

【问题讨论】:

标签: c# winforms


【解决方案1】:

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

如果它们包含在组控件或面板中,您可能希望执行以下操作:

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

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

How to get all children of a parent control?

How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?

【讨论】:

  • 文本框在一个组框中,但在不同的面板中。我尝试了你的建议,但仍然没有王牌。
  • 快速而肮脏的解决方案是识别文本框的直接父级并创建一个可以循环的串联列表。您可以为此使用 LINQ 的 Concat: var controls = panel1.Controls.Concat(panel2.Controls).Concat(panel3.Controls).Concat(...); foreach(控件中的控件子) { ... }。但是,这既快又脏,一旦开始添加更多文本框,就无法扩展。在那种情况下,你会想要我添加的链接中的内容。
  • 好的指甲。谢谢!我会研究你提供的链接。因为我还不知道 LINQ,所以会有点难
【解决方案2】:

您可以在迭代控件组时使用child.GetType() 获取控件的类型,然后将其与typeof(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";
     }
}

【讨论】:

    【解决方案3】:

    我认为您的代码没有任何问题。我怀疑您正在查看的控件是嵌套控件。

    我建议展平层次结构并获取所有(嵌套)控件,然后查找特定类型。

    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";
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 2016-06-26
      • 2010-12-06
      • 2017-02-03
      • 1970-01-01
      • 2020-07-27
      • 1970-01-01
      相关资源
      最近更新 更多