我编写了一个代码来从单个文本框的输入动态创建文本框。
当用户输入数据时,它应该自动生成这样的文本框......
我用过这段代码
private void textBoxInput_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBoxInput.Text))
{
//Get the number of input text boxes to generate
int inputNumber = Int32.Parse(textBoxInput.Text);
//Initialize list of input text boxes
inputTextBoxes = new List<TextBox>();
//Generate labels and text boxes
for (int i = 1; i <= inputNumber; i++)
{
//Create a new label and text box
Label labelInput = new Label();
TextBox textBoxNewInput = new TextBox();
//Initialize label's property
labelInput.Text = "Product" + i;
labelInput.Location = new Point(30, textBoxInput.Bottom + (i * 30));
labelInput.AutoSize = true;
//Initialize textBoxes Property
textBoxNewInput.Location = new Point(labelInput.Width, labelInput.Top - 3);
//Add the newly created text box to the list of input text boxes
inputTextBoxes.Add(textBoxNewInput);
//Add the labels and text box to the form
this.Controls.Add(labelInput);
this.Controls.Add(textBoxNewInput);
}
}
}
它工作得很好,但如果用户更改文本框中的值,我想更新该文本框,它应该动态更改。但它没有发生
我也尝试过其他条件
else
{
MessageBox.Show("Enter Value");
this.Controls.Clear();
this.Controls.Clear();
}
但它会删除此表单中的所有值。
我怎样才能只删除生成的文本框
更新 在这里,我根据@New Developer 的想法进行了更改
if (!string.IsNullOrEmpty(textBoxInput.Text))
{
//Get the number of input text boxes to generate
int inputNumber = Int32.Parse(textBoxInput.Text);
if (inputTextBoxes != null && inputTextBoxes.Count > inputNumber)
{
int removecount = inputTextBoxes.Count - inputNumber;
for (int i = 0; i < removecount; i++)
{
TextBox t = inputTextBoxes[inputTextBoxes.Count - 1];
inputTextBoxes.RemoveAt(inputTextBoxes.Count - 1);
t.Dispose();
}
return;
}
if (inputlabels != null && inputlabels.Count > inputNumber)
{
int removecount2 = inputlabels.Count - inputNumber;
for (int i = 0; i < removecount2; i++)
{
Label l = inputlabels[inputlabels.Count - 1];
inputlabels.RemoveAt(inputlabels.Count - 1);
l.Dispose();
}
return;
}
//Generate labels and text boxes
for (int i = 1; i <= inputNumber; i++)
{
//Create a new label and text box
Label labelInput = new Label();
TextBox textBoxNewInput = new TextBox();
//Initialize label's property
labelInput.Text = "Product" + i;
labelInput.Location = new Point(30, textBoxInput.Bottom + (i * 30));
labelInput.AutoSize = true;
//Initialize textBoxes Property
textBoxNewInput.Location = new Point(labelInput.Width, labelInput.Top - 3);
//Add the newly created text box to the list of input text boxes
inputTextBoxes.Add(textBoxNewInput);
inputlabels.Add(labelInput);
//Add the labels and text box to the form
this.Controls.Add(labelInput);
this.Controls.Add(textBoxNewInput);
}
}
}
并且还添加了
List<TextBox> inputTextBoxes = new List<TextBox>();
List<Label> inputlabels = new List<Label>();
在这里它工作,但价值每次都会改变