动态创建访问控件

动态创建访问控件

本文介绍了动态创建访问控件(c#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我尝试这样:

  foreach(面板控件中的控制小孩)
{
Response.Write(测试1\" );
if(child.GetType()。ToString()。Equals(System.Web.UI.WebControls.RadioButtonList))
{
RadioButtonList r =(RadioButtonList)child;
Response.Write(test2);
}
}

test1和test2不显示我的页面。这意味着这个逻辑有错误。
任何建议我可以做什么?

解决方案

每次回发后,您必须重新创建控件。



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



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



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



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

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

  if (Page.IsPostBack)
{
//在这里重新创建你的控件。
}

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

  myControl.ID =myId; 

我很难学习这个东西如何运作。一旦你学会了,你有权力在你手中。动态创建的控件开辟了一个新的可能性世界。



正如Frank所说:您可以使用is关键字来促进您的生活...

  if(child is RadioButtonList)



注意:
值得一提的是,页面,以供进一步参考。


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?

解决方案

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.

这篇关于动态创建访问控件(c#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 16:26