我已經編寫了一個代碼,用於從單個文本框的輸入中動態創建文本框。刪除動態創建的文本框
當用戶輸入數據就應自動生成這樣的文本框....
我已經使用這個代碼
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();
}
但它刪除此表中的所有值。
我怎麼能只刪除生成的文本框
UPDATE 我在這裏所做的更改按@New開發
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>();
這裏的工作但價值每次都在變化
代碼中存在一個錯誤。我將編輯代碼並在我的答案中更新。檢查一下。 –
好的朋友謝謝 –
我已經發布它作爲新的答案。請檢查。 –