Adding User Control Dynamically in ASP.NET

走远了吗. 提交于 2019-12-13 02:35:55

问题


I know this question was asked many times, but still my problem is not solved,

I'm trying to iterate on a list of objects, and fill a template "user control" with that object, like result list of a search.

in these user controls there is a linkButton which should redirect to another page, when I click on that linkButton nothing happens, I googled it but no satisfying answer.

here is the code, I'll illustrate with button instead of a user control:

protected override void OnInit(EventsArgs e)
{
   for(int i=0;i<10;i=i+1)
   {
        Button b = new Button();
        b.ID = "Button" + i;
        b.Click += new System.EventHAndler(this.Button_OnClick);
        Controls.Add(b);
    }
 base.OnInit(e);
}

private void Button_OnClick(object Sender,System.EventsArgs e)
{
     Response.Redirect("~/Some.aspx");
}

public override void VerifyRenderingInServerForm(Control control)
{
    return;
}

It never calls the Button_OnClick method.

Thanks in advance.


回答1:


The button will never fire because is not a child of a server form control.

If there is no form control yet, you need to add it:

<form id="form1" runat="server">
</form>

And replace

  Controls.Add(b);

With

  form1.Controls.Add(b);



回答2:


try this

for (int i = 0; i < 10; i = i + 1)
{
    Button b = new Button();
    b.ID = "Button" + i;
    b.Click += new EventHandler(b_Click); 
    Controls.Add(b);
}

void b_Click(object sender, EventArgs e)
{
    //some code
}



回答3:


Use Page_Init instead of OnInit.

Calling base.OnInit before creating the buttons might also work.



来源:https://stackoverflow.com/questions/9718008/adding-user-control-dynamically-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!