Event Handler for a dynamically created control

I am dynamically creating an asp.net RadioButton and inserting it into my web page:

RadioButton rb = new RadioButton();
rb.ID  = "rb" + ReportPKey;
rb.Text = "ReportName";
phUiControls.Controls.Add(rb);

I have the following method:

protected void rb_CheckedChanged( object sender, EventArgs e )
{
    // stuff
}

How do I wire this up so that rb_CheckedChanged is fired when rb is clicked?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

rb.CheckedChanged += rb_CheckedChanged

Method 2

One way to do it with an anonymous delegate (clean for these types of scenarios):

var rb = new RadioButton{ ID = "rb" + ReportPKey, Text = "ReportName" };
phUiControls.Controls.Add( rb );

rb.CheckedChanged += (sender, e) => {
    // event handler code
};

Or (as several other people have pointed out):

rb.CheckedChanged += rb_CheckedChanged

In context of the page lifecycle:

protected override OnInit( EventArgs e ){
    BuildDynamicControls();
    base.OnInit( e );
}

private void BuildDynamicControls(){
    var rb = new RadioButton{ ID = "rb" + ReportPKey, Text = "ReportName" };
    phUiControls.Controls.Add( rb );

    rb.CheckedChanged += (sender, e) => {
        // event handler code
    };
}

Method 3

RadioButton rb = new RadioButton();
rb.ID  = "rb"+ReportPKey;
rb.Text = ReportName  ;
rb.CheckedChanged += rb_CheckedChanged
phUiControls.Controls.Add(rb);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x