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

如何在C#asp.net中动态创建文本框?,c#,dynamic,textbox,C#,Dynamic,Textbox,对于我面临的问题,我需要一些建议或想法 我想从输入字符串动态创建一个文本框,如示例“11211” 当它根据上面的字符串读取第一个字符时,在本例中为“1”,将创建一个背景颜色为黄色的文本框 循环将继续水平创建文本框,直到读取完上面字符串中的所有字符 代码片段如下所示:- foreach (XmlNode xn in list1) { string name = xn["BinCode"].InnerText; disGood.Text = name;

对于我面临的问题,我需要一些建议或想法

我想从输入字符串动态创建一个文本框,如示例“11211”

当它根据上面的字符串读取第一个字符时,在本例中为“1”,将创建一个背景颜色为黄色的文本框

循环将继续水平创建文本框,直到读取完上面字符串中的所有字符

代码片段如下所示:-

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();
        }
}
foreach(列表1中的xmlnodexn)
{
字符串名称=xn[“BinCode”]。InnerText;
disGood.Text=名称;
字符串输入=名称;
disOccupied.Text=input.Length.ToString();
char[]b=name.ToCharArray();
foreach(b中的字符c)
{
TextBox[]thetextboxs=新的TextBox[1];
for(int i=0;i
一些样品或想法将被高度推荐


多谢各位

我看到很多冗余。例如:你的文本框数组是无用的,因为你总是在每次迭代中创建一个文本框。对额外变量
input
b
的赋值是额外但不需要的操作。试试这个:

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?
    }
}

要动态创建并水平显示文本框,请使用以下代码:

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

this.Controls.Add(thetextboxs[i])User2012384-我正在获取此错误-类型为“TextBox”的控件“ctl02”必须放置在runat=server的表单标记中。感谢Martin,我已删除了冗余并尝试运行您提到的方法。它也有效。谢谢。:)找到了如何水平显示文本框。将它们添加到TableLayoutPanel控件时,只需指定列和行。TableLayoutPanel(文本框、列、行);简单:)