1

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.

2
  • I don't see anything wrong in your sample, can you post the actual code? Commented Mar 15, 2012 at 10:48
  • I've just edited the code, this is what I'm having now, I want the new buttons to fire event. I'm using VerifyRenderingInServerForm method, otherwise there will be an error. Commented Mar 15, 2012 at 11:01

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Where should I place <form id="form1" runat="server"> </form> exactly? after <head runat="server"> or before that?
It's working :) thanks a lot, I was strugling for three days.
0

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
}

1 Comment

Yes, I'm already doing this, but it never reaches that method.
0

Use Page_Init instead of OnInit.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.