增加文本框名称中的数字

时间:2009-01-05 02:38:59

标签: c#

public void test()
    {
        List<int> list = new List<int>();
        list.Add(1);
        list.Add(2);
        list.Add(3);
        for (int i = 1; i <= list.Count; i++)
        {

            textBx.Text = list[i].ToString();
            // I want it to be textBx1.Text = list[1].ToString();
                               textBx2.Text = list[2].ToString();
                               textBx3.Text = list[3].Tostring();
                               etc.
              // I can't create textbox dynamically as I need the text box to be placed in specific places in the form . How do I do it the best way? 


        }


    }

2 个答案:

答案 0 :(得分:5)

听起来像是Controls.Find()的工作。您可以动态构建字符串并使用该名称搜索TextBox:

 var textBox = this.Controls.Find("textBx" + i, true) as TextBox;
 textBox.Text = list[i].ToString();

这有点难看,因为它取决于TextBoxes的命名约定。也许更好的解决方案是在循环之前缓存TextBox的列表:

var textBoxes = new[] { textBx1, textBx2, textBx3 };

然后你可以简单地索引到数组:

textBoxes[i].Text = list[i].ToString();

答案 1 :(得分:2)

+1来Matt。这是一个有效的完整解决方案:

        string TextBoxPrefix = "textBx";
        foreach (Control CurrentControl in this.Controls)
        {
            if (CurrentControl is TextBox)
            {
                if (CurrentControl.Name.StartsWith(TextBoxPrefix)) {

                    int TextBoxNumber = System.Convert.ToInt16(CurrentControl.Name.Substring(TextBoxPrefix.Length));

                    if (TextBoxNumber <= (list.Count - 1))
                    {
                        CurrentControl.Text = list[TextBoxNumber].ToString();
                    }
                }
            }
        }