【问题标题】:Create Control using loop then append name with string [duplicate]使用循环创建控件,然后将名称附加到字符串 [重复]
【发布时间】:2013-12-07 12:09:40
【问题描述】:

有人知道如何将字符串附加到变量名吗?

public void editForm(DataGridView dg)
{
   for(int i=0; i<=dg.Columns.Count-1;i++)
   {
      TextBox txt=new TextBox();   //I want to append i to txt. like -->TextBox txt&i
   }
}

然后我将创建的文本框添加到表单中。

【问题讨论】:

标签: c#


【解决方案1】:

这在C# 中是不可能的。

您可以使用某种集合来实现类似的功能,例如数组,

public void editForm(DataGridView dg)
{
    TextBox[] textBoxes = new TextBox[dg.Columns.Count];
    for(int i = 0; i <= dg.Columns.Count-1; i++)
    {
        textBoxes[i] = new TextBox();  
    }
}

不过,您可以使用Enumerable.Range 做一些更好的事情,

public void editForm(DataGridView dg)
{
    var textBoxes = 
        Enumerable.Range(0, dg.Columns.Count)
                  .Select(i => new TextBox())
                  .ToArray();
}

无论哪种方式,您都可以将文本框添加到表单中。

【讨论】:

    猜你喜欢
    • 2018-10-18
    • 2019-12-28
    • 2014-11-11
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 2012-05-24
    • 2017-07-10
    • 2014-06-12
    相关资源
    最近更新 更多