Event handlers and dynamically created controls

Discussion in 'ASP .Net' started by Guest, Jan 25, 2007.

  1. Guest

    Guest Guest

    I have created a method that dynamically creates a single button control (as
    a proof-of-concept, I would like to be able to create multiple buttons). I
    set properties on this control including an event handler for the click
    event. The problem is that when I click the button on the page and view the
    locals window in debug mode, I don't see any information on the button
    control.

    Say, I want to create a variable number of buttons based on some user input,
    these buttons would be created with an ID=Btn1, ID=Btn2, etc. And say that I
    want to have all of these buttons call the same event handler when clicked.
    In this event handler I would like to be able to interrogate the button
    object that raised the event to determine which id number it is.
    Here is the code:

    private void createControl()
    {
    // Create and configure a single button control.
    Button btn = new Button();
    btn.ID = "btn1";
    btn.Width = Unit.Pixel(75);
    btn.Height = Unit.Pixel(25);
    btn.Text = "Click Me";
    EventArgs e = new EventArgs();
    btn.Click += new EventHandler(this.btn_Click);
    btn.Style.Add(HtmlTextWriterStyle.Left,"100px");
    btn.Style.Add(HtmlTextWriterStyle.Top,"100px");
    btn.Style.Add(HtmlTextWriterStyle.Position,"absolute");

    // Add this control to the form.
    this.form1.Controls.Add(btn);
    }

    private void btn_Click(object sender, System.EventArgs e)
    {
    Response.Write("Hello from dynamic control: ");
    }

    Any ideas, or comments would be greatly appreciated!
    Thanks,
    - Mike
     
    Guest, Jan 25, 2007
    #1
    1. Advertisements

  2. Guest

    senfo Guest

    private void btn_Click(object sender, System.EventArgs e)
    {
    Button btn;

    if ((btn = sender as Button) != null)
    {
    Response.Write("Hell from dynamic control: " + btn.ID);
    }
    }

    Hope that helps,
     
    senfo, Jan 26, 2007
    #2
    1. Advertisements

  3. Guest

    Guest Guest

    Sean,
    Thanks, that worked perfectly!
    - Mike

     
    Guest, Jan 26, 2007
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.