I have used the below code to dynamically create textboxes by giving the total number of textboxes initially. After i enter values to these textboxes, how can i fetch the values from it. Like if i give count as 3, 3 textboxes will be created. Now, i enter data to each textbox. How can i read the values i entered into these texboxes.
我已经使用下面的代码通过最初给出文本框的总数来动态创建文本框。在我为这些文本框输入值后,如何从中获取值。就像我将数量计为3,将创建3个文本框。现在,我向每个文本框输入数据。我如何阅读我输入这些texbox的值。
int a = 1;
public Form1()
{
InitializeComponent();
}
public System.Windows.Forms.TextBox AddNewTextBox()
{
System.Windows.Forms.TextBox txt = new System.Windows.Forms.TextBox();
this.Controls.Add(txt);
txt.Top = a * 25;
txt.Left = 100;
txt.Name = "txt" + this.a.ToString();
txt.Text = "TextBox " + this.a.ToString();
a = a + 1;
return txt;
}
private void button1_Click(object sender, EventArgs e)
{
int i;
int count = Int16.Parse(counttxt.Text.ToString());
for (i = 1; i <= count; i++)
{
AddNewTextBox();
}
}
2 个解决方案
#1
1
string allTextBoxValues = "";
foreach (Control childc in Controls) {
if (childc is TextBox && childc.Name.Contains("txt"))
allTextBoxValues += ((TextBox)childc).Text + ",";
}
#2
2
Hold a reference to the dynamically generated TextBox
in a variable of type array
or list
.
在类型为array或list的变量中保存对动态生成的TextBox的引用。
Beside that if u want the value from TextBox
that was named txt1
除此之外,如果你想要来自TextBox的名为txt1的值
string value = this.Controls["txt1"].Text
#1
1
string allTextBoxValues = "";
foreach (Control childc in Controls) {
if (childc is TextBox && childc.Name.Contains("txt"))
allTextBoxValues += ((TextBox)childc).Text + ",";
}
#2
2
Hold a reference to the dynamically generated TextBox
in a variable of type array
or list
.
在类型为array或list的变量中保存对动态生成的TextBox的引用。
Beside that if u want the value from TextBox
that was named txt1
除此之外,如果你想要来自TextBox的名为txt1的值
string value = this.Controls["txt1"].Text