在 C# 程序中使用动态文本框
Using Dynamic Textboxes in C# Program
我正在尝试根据 TextBox1 中的数字创建 TextBox 的数量,并且我想在我的程序中使用每个 TextBox 值。他们的名字变成了 txtbx0, txtbx1... 但是当我想在我的程序中使用时,它给出了错误 "The name 'txtbx1' does not exist in the current context"。我如何在我的程序中使用它们?
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int y = Convert.ToInt32(textBox1.Text);
TextBox[] txtbx = new TextBox[y];
for (int i = 0; i < y; i++)
{
txtbx[i]= new TextBox();
txtbx[i].Location = new Point(20, i * 50);
txtbx[i].Size = new Size(100,50);
txtbx[i].Name = "txtbx"+i.ToString();
txtbx[i].Text = txtbx[i].Name;
flowLayoutPanel1.Controls.Add(txtbx[i]);
}
}
按照您现在的方式,可以使用数组 txtbx[whateverNumber]
访问文本框。为了使它们可以在您发布的方法之外访问,您需要使 txtbx
数组成为 class 成员而不是方法范围的变量。
类似于:
class Form1 : Form
{
TextBox[] txtbx;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int y = Convert.ToInt32(textBox1.Text);
txtbx = new TextBox[y]; // Now this references the class member
for (int i = 0; i < y; i++)
... etc.
}
}
通过名称单独访问它们并不真正可行,因为您必须为它们中的每一个创建 class 个成员变量,但您事先不知道要创建多少个。像你正在做的数组方法要好得多。您可以使用 txtbx[0]
到 txtbx[numBoxes - 1]
.
以其他方法访问它们
我正在尝试根据 TextBox1 中的数字创建 TextBox 的数量,并且我想在我的程序中使用每个 TextBox 值。他们的名字变成了 txtbx0, txtbx1... 但是当我想在我的程序中使用时,它给出了错误 "The name 'txtbx1' does not exist in the current context"。我如何在我的程序中使用它们?
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int y = Convert.ToInt32(textBox1.Text);
TextBox[] txtbx = new TextBox[y];
for (int i = 0; i < y; i++)
{
txtbx[i]= new TextBox();
txtbx[i].Location = new Point(20, i * 50);
txtbx[i].Size = new Size(100,50);
txtbx[i].Name = "txtbx"+i.ToString();
txtbx[i].Text = txtbx[i].Name;
flowLayoutPanel1.Controls.Add(txtbx[i]);
}
}
按照您现在的方式,可以使用数组 txtbx[whateverNumber]
访问文本框。为了使它们可以在您发布的方法之外访问,您需要使 txtbx
数组成为 class 成员而不是方法范围的变量。
类似于:
class Form1 : Form
{
TextBox[] txtbx;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int y = Convert.ToInt32(textBox1.Text);
txtbx = new TextBox[y]; // Now this references the class member
for (int i = 0; i < y; i++)
... etc.
}
}
通过名称单独访问它们并不真正可行,因为您必须为它们中的每一个创建 class 个成员变量,但您事先不知道要创建多少个。像你正在做的数组方法要好得多。您可以使用 txtbx[0]
到 txtbx[numBoxes - 1]
.