【问题标题】:find dynamically added controls from container从容器中找到动态添加的控件
【发布时间】:2014-07-15 23:59:08
【问题描述】:

我在下拉选择的索引更改事件上生成动态文本框控件。

  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>();

但它也不起作用。

谁能告诉我这里出了什么问题。

谢谢

【问题讨论】:

  • 我添加了标签。谢谢
  • CustomAttributes.Controls.FindControl() 不存在?
  • 为什么FindControl 不适合你?
  • 您需要递归搜索,因为您的 TextBox 是 innerdiv 的子代,而不是 CustomAttributes 直接的子代。 stackoverflow.com/questions/253937/…stackoverflow.com/questions/4955769/…。如前所述,FindControl 应该可以工作,因为您也为 TextBox 提供了 ID
  • @SajithA.K.它在那里,我试过了。它返回给我 null

标签: c# asp.net dynamic findcontrol


【解决方案1】:

我在谷歌上搜索了这个问题后终于找到了原因。这个问题的问题是视图状态。

在 asp.net 中,当页面回发时,它会丢失动态生成的控件的视图状态。所以为了克服这个问题,我在页面加载事件中重新创建了控件,当它被回发时。这样控件将被添加回当前页面,我可以在单击事件的按钮中找到这些控件。

感谢大家的时间和指导。

【讨论】:

    【解决方案2】:
    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())
    

    【讨论】:

    • 不工作。文本框的计数为 0。没有找到文本框。
    • 上述行工作,在foreach循环之后立即尝试。问题是在像Button.OnClick 这样的另一个事件中,执行回发,呈现要重新初始化(或刷新)的页面;因此,我们失去了动态控制。
    • 是的,我也阅读了一些关于此的主题。你知道如何保存控件状态,以便我可以在另一个事件中找到它们,比如按钮单击??
    • 您可以在Page.Load 或另一个事件处理程序上重新创建控件以将控件保留在页面上。由于Button.OnClick 将产生post 操作,您应该能够从结果中提取文本框的值。不幸的是,我无法使用我的笔记本电脑进行测试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多