【问题标题】:Dynamically create controls in aspx?在aspx中动态创建控件?
【发布时间】:2011-04-03 06:06:37
【问题描述】:

我尝试了几种方法在 .aspx 页面的代码隐藏中创建一些控件。我有这些问题:

1) 每个组件的名称
2) 这些组件的位置
3) 在方法事件中或完全在代码中访问这些组件

我想创建几个<asp:textbox> 并将它们放在表格行中。然后我想获得这些文本框的价值并用它们做一些事情。

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    Retaining State for Dynamically Created Controls in ASP.NET applications 上试试这个演示。

    这是一个非常简单的演示,介绍如何向页面添加控件,并让后续回发识别您之前的修改。基本上文本框的数量被保存到ViewState。它将循环创建 n 个文本框。

    您可以根据需要进行修改以适应不同的控件和命名方案。如果你愿意,你也可以改用Session

    您可能想要的修改:

    private void createControls()
    {
        int count = this.NumberOfControls;
    
        for(int i = 0; i < count; i++)
        {
            TextBox tx = new TextBox();
            tx.ID = "ControlID_" + i.ToString();
    
            //Add the Controls to the container of your choice
            MyContainer.Controls.Add(tx);
        }
    } 
    

    【讨论】:

    • 这是你链接到的一个很好的例子。非常简洁,它避免了我个人无法忍受的 PreInit 废话。
    猜你喜欢
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    • 2011-06-27
    相关资源
    最近更新 更多