C#使用String来识别/使用文本框?

时间:2012-04-10 14:49:27

标签: c# textbox

我有6行6个文本框,共36个。第一行,第一行称为L1N1,行第一行,第二行是L1N2等。我想使用字符串动态地为这些文本框分配值...这可以在C#中完成吗? E.g。

    private void Generate_Click(object sender, EventArgs e)
    {
        int[,] numbers = new int[6, 6];
        int lin = 0;
        while (lin < 6)
        {
            lin++;
            int num = 0;
            while (num < 6)
            {
                num++;
                Random random = new Random();
                int randomNum = random.Next(1, 45);
                "L" + lin + "N" + num /* <--here is my string (L1N1) i want to 
                                          set my textbox(L1N1).text to a value
                                          randomNum!*/

7 个答案:

答案 0 :(得分:2)

当然,WebPage为您提供了一个很好的FindControl:

TextBox tx = FindControl("L" + lin + "N" + num) as TextBox;

答案 1 :(得分:0)

List<TextBox> listOfTextBoxes = new List<TextBox>();
...initialization of list.... 
foreach(TextBox tb in listOfTextBoxes)
{
Random r = new Random();
tb.Text = r.Next(1,45).ToString();
}

答案 2 :(得分:0)

你不能使用FindControl API并设置.text属性吗?

答案 3 :(得分:0)

private void formMain_Load(object sender, EventArgs e)
{
     this.Controls.Find("Your Concatenated ID of control ex: L1N2", true);
}

foreach(var cont in form.Controls)
{
     if(cont is TextBox) dosmth;
}

答案 4 :(得分:0)

如果是webform :(只是找出表单索引)

    protected void Generate_Click(object sender, EventArgs e)
    {
        foreach(Control item in Page.Controls[3].Controls)
        {
            if(item.GetType().ToString().ToLower().Contains("textbox"))
            {
                Random rnd = new Random();
                TextBox txt = (TextBox)item;
                System.Threading.Thread.Sleep(20);
                txt.Text = rnd.Next(1, 45).ToString();
            }
        }
    }

答案 5 :(得分:0)

Form.Controls有一个FindByName方法,因此您可以构建控件名称并使用它。但它并不光彩。

就我个人而言,我要以编程方式从TextBox [6,6]创建控件,或者按下 将对它们的引用从Form.Controls加载到数组[6,6]作为一个关闭。

获得阵列后,您可以找到它的各种用途。

答案 6 :(得分:-1)

我赞同Jon Skeet的观点。如果您希望能够通过某些行/列系统找到控件,最简单的方法是将控件本身放入一个集合中,以便以类似的方式对它们建立索引:

var textboxes = new TextBox[6][];
textboxes[0] = new TextBox[]{txtL1N1, txtL1N2, txtL1N3, txtL1N4, txtL1N5, txtL1N6};
//create the rest of the "lines" of TextBoxes similarly.

//now you can reference the TextBox at Line X, number Y like this:
textboxes[X-1][Y-1].Text = randomNum.ToString();

现在,如果您真的想通过某个字符串值访问这些文本框,您可以使用Tag属性,这是大多数控件的通用属性。您还可以根据某个系统命名所有文本框。然后,一个小Linq可以得到你想要的文本框:

this.Controls.OfType<TextBox>()
   .Single(t=>t.Tag.ToString() == "L1N1").Text = randomNum.ToString();

然而,明白这将非常缓慢;您将在每次需要时搜索表单上存在的所有控件的完整集合。索引会更快。