[英]Deleting dynamically created textbox
今天是个好日子。
我正在创建函数,其中我根据下拉列表中的选定值动态生成文本框。
这是代码。
comboboxNameHolder = ((ComboBox)sender).Name;
string comboboxNoHolder =comboboxNameHolder.Replace("cbFunctionList", "");
comboboxNo = Int32.Parse(comboboxNoHolder);
funcSelected = ((ComboBox)sender).SelectedItem.ToString();
for (int i = 0; i < optionList1.GetLength(0); i++)
{
if (funcSelected == optionList1[i, 0])
{
funcNoOfFields = optionList1[i, 1];
}
}
if (lineFieldController[comboboxNo, 1] == 0)
{
fieldCounter = Int32.Parse(funcNoOfFields);
lineFieldController[comboboxNo, 1] = fieldCounter;
inputField1 = new TextBox[fieldCounter];
for (int i = 0; i < fieldCounter; i++)
{
btnAddField0.Visible = false;
inputField = new TextBox();
inputField.Font = new Font("Microsoft Sans Serif", 11.25f);
inputField.Size = new Size(75, 24);
inputField.Location = new Point(positionController[comboboxNo, 0], positionController[comboboxNo, 1]);
inputField.Name = "txtLine" + comboboxNo.ToString() + "Variable" + i.ToString();
this.Controls.Add(inputField1[i]);
positionController[comboboxNo, 0] += 81;
}
}
现在我想在lineFieldController
不等于零时使用相同的函数,这意味着该行中已经创建了文本框。 当用户在下拉列表中选择另一个值时,字段数量将通过删除现有字段然后根据所选项目创建新字段来更改。
如何删除我创建的文本框? 我尝试按名称调用它,但它不起作用。
else
{
for(int i = 0; i < lineFieldController[comboboxNo, 1]; i++)
{
string name = "txtLine" + comboboxNo.ToString() + "Variable" + i.ToString();
TextBox tb = this.Controls.Find(name, true);
}
}
期待您的善意回应
您可以将您创建的所有控件放入列表中,并保留对在运行时创建的控件的引用。
喜欢
public class Form1
{
List<Control> createdList = new List<Control>(); // class field
void combobox_SelectedIndexChanged()
{
// removing controls were created before
foreach (var created in createdList)
{
this.Controls.Remove(created);
created.Dispose();
}
createdList.Clear(); // all created controls from previous index changed should be removed here
// add each control you are creating to the createList additionally
inputField1 = new TextBox[fieldCounter];
for (int i = 0; i < fieldCounter; i++)
{
btnAddField0.Visible = false;
inputField = new TextBox();
createdList.Add(inputField); //store reference
/// skipping init code
this.Controls.Add(inputField1[i]);
positionController[comboboxNo, 0] += 81;
}
}
}
另一种选择是在窗体上添加面板作为正在创建的所有控件的占位符。 你必须改变this.Controls.Add(inputField1[i]);
到panelCreated.Controls.Add(inputField1[i]);
然后您可以从面板中获取所有控件并删除它们,而无需名称搜索,如下所示
foreach (Control created in panelCreated.Controls)
created.Dispose();
panelCreated.Controls.Clear();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.