从容器中查找动态添加的控件
本文关键字:添加 控件 动态 查找 | 更新日期: 2023-09-27 18:05:13
我正在生成动态文本框控件的下拉选择索引更改事件。
protected void ddlCategories_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (Attributes attribute in getAllAttributes(Convert.ToInt32(ddlCategories.SelectedValue)))
{
Panel div = new Panel();
div.Attributes.Add("class", "form-group");
HtmlGenericControl lbl = new HtmlGenericControl("label");
lbl.Attributes.Add("class", "col-lg-2 control-label");
lbl.InnerText = attribute.Name;
Panel innerdiv = new Panel();
innerdiv.Attributes.Add("class", "col-lg-10");
TextBox txt = new TextBox();
txt.ID = attribute.ID.ToString();
txt.Attributes.Add("class", "form-control");
innerdiv.Controls.Add(txt);
div.Controls.Add(lbl);
div.Controls.Add(innerdiv);
CustomAttributes.Controls.Add(div);
}
}
现在,在用户填写表单中的值之后,我想获得动态生成的控件的值。但是CustomAttributes.findControls("")
不适合我。它总是返回null
我也试过
var textBoxesInContainer = CustomAttributes.Controls.OfType<TextBox>();
,但它也不起作用。
谁能告诉我这里出了什么问题?谢谢
最后我在谷歌上找到了原因。这个问题中的问题是视图状态。
在asp.net中,当页面返回时,它将失去动态生成控件的视图状态。因此,为了解决这个问题,我在页面加载事件中重新创建了控件,当它被发回时。通过这种方式,控件将被添加回当前页面,并且我可以在click event上的按钮中找到这些控件。
感谢大家的指导。
Panel div = new Panel();
Panel innerdiv = new Panel();
TextBox txt = new TextBox();
innerdiv.Controls.Add(txt);
div.Controls.Add(innerdiv);
CustomAttributes.Controls.Add(div);
你的CustomAttributes
持有Panel
。试试这个:
var textboxes = CustomAttributes.Controls.OfType<Panel>()
.Select(p => p.Controls.OfType<Panel>().First())
.Select(p => p.Controls.OfType<TextBox>().First())