簡體   English   中英

如何在C#asp.net中動態創建文本框?

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

對於所面臨的問題,我需要一些建議或想法。

我想根據輸入字符串(例如“ 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();
        }
}

強烈建議您提供一些示例或想法。

謝謝。

我看到很多冗余。 例如:您的文本框數組是無用的,因為您總是在每次迭代期間創建一個文本框。 額外變量inputb的分配是額外的,但不需要的操作。 嘗試這個:

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,
    };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM