【问题标题】:For Loop increasing textBox ID. C# Windows FormFor 循环增加文本框 ID。 C# Windows 窗体
【发布时间】:2020-01-02 22:21:11
【问题描述】:

我有 100 个textBoxes,我想使用 for 循环为所有这些设置一个值。

for(int i=0; i<100; i++)
{
    textBox1.AppendText("a");
}

textBox ID 必须像textBox1textBox2textBox3 等一样动态更改...

我该怎么做?

【问题讨论】:

  • 您使用的是什么平台? ASP.NET、Windows 窗体、Xamarin 窗体???
  • 我使用的是 Windows 窗体。
  • 将它们存储在一个数组中。

标签: c# winforms for-loop


【解决方案1】:

试试这个代码:

for (int i = 1; i <= numberOfTextBoxes; i++)
{
    var tb = this.Controls.Find("textBox" + i, true).FirstOrDefault();
    if(tb != null)
      tb.Text = "hello " + i;
}

More on Find method.

【讨论】:

    【解决方案2】:

    将所有文本框放在一个列表中。

    或者把它们放在一个控件中然后查询它们。使用 typeof TextBox 调用此方法。

    public IEnumerable<Control> GetAll(Control control,Type type)
    {
        var controls = control.Controls.Cast<Control>();
    
        return controls.SelectMany(ctrl => GetAll(ctrl,type))
                                  .Concat(controls)
                                  .Where(c => c.GetType() == type);
    }
    

    编辑:如 cmets 中所述,您还可以将表单传递给此方法。 或者直接从表单中查询控件。

    【讨论】:

    • 也许吧。但它可能是 Winforms。
    • 您不需要将它们放在控件中。您只需要枚举 Controls 集合并选择正确的集合即可。
    • 或将表单传递给您的方法。
    • 新。为什么不.OfType
    • OfType 在这里不一样 - GetAll 调用是递归的。
    猜你喜欢
    • 2021-09-23
    • 2015-04-15
    • 2012-01-23
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    相关资源
    最近更新 更多