问题
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