简体   繁体   English

如何在C#asp.net中动态创建文本框?

[英]How to create textbox dynamically in C# asp.net?

I would need some advice or ideas on the problem I'm facing. 对于所面临的问题,我需要一些建议或想法。

I would like to to create a textbox dynamically from an input string like example '11211'. 我想根据输入字符串(例如“ 11211”)动态创建一个文本框。

When it read the first character based on the string above, in this case '1', a textbox with background color yellow would be created. 当它根据上面的字符串读取第一个字符时,在这种情况下为“ 1”,将创建一个背景颜色为黄色的文本框。

The loop would continue creating textboxes horizontally till finished reading all the characters in string above. 循环将继续水平创建文本框,直到完成读取上面字符串中的所有字符为止。

Snippet of the code is as below :- 代码片段如下:

foreach (XmlNode xn in list1)

{

       string name = xn["BinCode"].InnerText;

       disGood.Text = name;

       string input = name;

       disOccupied.Text = input.Length.ToString();

       char[] b = name.ToCharArray();

       foreach (char c in b)
       {

           TextBox[] theTextBoxes = new TextBox[1];

           for (int i = 0; i < theTextBoxes.Length; i++)
           {
               theTextBoxes[i] = new TextBox();

               if (c.ToString() == "1")
               {
                   theTextBoxes[i].BackColor = Color.Yellow;
               }

           }

            disGood.Text = c.ToString();
        }
}

Some sample or ideas would be high recommended. 强烈建议您提供一些示例或想法。

Thank you. 谢谢。

I see a lot of redundancies. 我看到很多冗余。 For example: your array of textboxes is useless, since you always create one textbox during each iteration. 例如:您的文本框数组是无用的,因为您总是在每次迭代期间创建一个文本框。 The assignment to the extra variable input and b are extra, but unneeded operations. 额外变量inputb的分配是额外的,但不需要的操作。 Try this: 尝试这个:

foreach (XmlNode xn in list1)
{
    string name = xn["BinCode"].InnerText;
    disGood.Text = name;
    disOccupied.Text = name.Length.ToString();
    foreach (char c in name) // You can iterate through a string.
    {
        TextBox theTextBox = new TextBox();
        if (c == '1') // Compare characters.
        {
            theTextBox.BackColor = Color.Yellow;
        }
        Controls.Add(theTextBox); // Add the textbox to the controls collection of this parent control.
        disGood.Text = c.ToString(); // This will only show the last charachter. Is this as needed?
    }
}

To dynamically create and display textbox's horizontally use the below code: 要动态创建和水平显示文本框,请使用以下代码:

  TextBox t = new TextBox()
    {
         //To display textbox horizontally use the TableLayoutPanel object
         TableLayoutPanel(TextBox, Column, Row);
         //add any properties specs,
         //more property specs,
    };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM