単一のテキスト ボックスの入力から動的にテキスト ボックスを作成するコードを作成しました。
ユーザーがデータを入力すると、このようなテキストボックスが自動的に生成されます....
このコードを使用しました
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条件を試しました
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>();
ここでは機能しますが、値は毎回変わります