Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
590 views
in Technique[技术] by (71.8m points)

asp.net - Accessing controls created dynamically (c#)

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)?

I tried this:

    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" and "test2" dont show up in my page. That means something is wrong with this logic. Any suggestions what could I do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You must recreate your controls after each postback.

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.

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.

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

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

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.

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

if(child is RadioButtonList)


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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...