[英]find dynamically added controls from container
我在下拉選定的索引更改事件時生成動態文本框控件。
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中,當頁面回發時,它會丟失動態生成控件的viewstate。 因此,要解決此問題,我會在頁面加載事件回發時重新創建控件。 這樣,控件將被添加回到當前頁面,並且我可以在click事件的按鈕中找到這些控件。
感謝大家的時間和指導。
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())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.