访问动态创建的控件 (c#)控件、动态

由网友(怼)分享简介:在 (c#) 后面的代码中,我动态创建了一些 RadioButtonLists,其中每个 RadioButtons 都有更多.我把所有控件放到一个特定的面板上.我需要知道的是以后如何访问这些控件,因为它们不是在 .aspx 文件中创建的(通过从工具箱中拖放)?In my code behind (c#) I dyna...

在 (c#) 后面的代码中,我动态创建了一些 RadioButtonLists,其中每个 RadioButtons 都有更多.我把所有控件放到一个特定的面板上.我需要知道的是以后如何访问这些控件,因为它们不是在 .aspx 文件中创建的(通过从工具箱中拖放)?

In my code behind (c#) I dynamically created some RadioButtonLists with more RadioButtons in each of them. I put all controls to a specific Panel. What I need to know is how to access those controls later as they are not created in .aspx file (with drag and drop from toolbox)?

我试过了:

    foreach (Control child in panel.Controls)
    {
        Response.Write("test1");
        if (child.GetType().ToString().Equals("System.Web.UI.WebControls.RadioButtonList"))
        {
            RadioButtonList r = (RadioButtonList)child;
            Response.Write("test2");
        }   
    }

test1"和test2"没有出现在我的页面中.这意味着这个逻辑有问题.有什么建议我可以做什么?

"test1" and "test2" dont show up in my page. That means something is wrong with this logic. Any suggestions what could I do?

推荐答案

您必须在每次回发后重新创建控件.

You must recreate your controls after each postback.

ASP.NET 是无状态的,也就是说,当您将页面回发到服务器时,您动态创建的控件将不再是页面的一部分.

ASP.NET is stateless, that is, when you postback a page to the server, your dynamically created controls won't be part of the page anymore.

上周我不得不再次克服这种情况.

Last week I had to overcome this situation once more.

我做了什么?我保存了用于在 Session 对象中创建控件的数据.在 PageLoad 方法中,我传递了相同的数据来重新创建动态控件.

What did I do? I saved the data that I used to create the controls inside Session object. On PageLoad method I passed that same data to recreate the dynamic controls.

我的建议是:编写一个方法来创建动态控件.

What I suggest is: Write a method to create the dynamic controls.

在 PageLoad 方法中检查是否是回发...

On PageLoad method check to see if it's a postback...

if(Page.IsPostBack)
{
   // Recreate your controls here.
}

一件非常重要的事情:为您动态创建的控件分配唯一的 ID,以便 ASP.NET 可以重新创建绑定其现有事件处理程序的控件、恢复其 ViewState 等.

A really important thing: assign unique IDs to your dynamically created controls so that ASP.NET can recreate the controls binding their existing event handlers, restoring their ViewState, etc.

myControl.ID = "myId";

我很难了解这东西是如何工作的.一旦你学会了,你就掌握了权力.动态创建的控件开辟了一个充满可能性的新世界.

I had a hard time to learn how this thing works. Once you learn you have power in your hands. Dynamically created controls open up a new world of possibilities.

正如弗兰克所说:您可以通过这种方式使用is"关键字来方便您的生活......

As Frank mentioned: you can use the "is" keyword this way to facilitate your life...

if(child is RadioButtonList)

注意:值得一提的是 ASP.NET 页面生命周期概述 页面MSDN 供进一步参考.

Note: it's worth to mention the ASP.NET Page Life Cycle Overview page on MSDN for further reference.

阅读全文

相关推荐

最新文章