简体   繁体   中英

firing Event for every RadioButton

I'm creating a radio button in C# code for a WinRT application.

My code:

for(var l = 0; l < 4; l++) {
    RadioButton radio = new RadioButton();
    radio.Checked += (sender,arg)=>{ //sender };
    stackpanel.children.add(radio);
}

Now I add those radio buttons in page and I need to know which radio button is checked but when event fires it's sent to me only the last button. How do I make an event for every button so that when someone checks Button 1 I can send a message box: "you checked button 1"?

Use the CheckChangedEvent. Try to use this in your for-loop:

     RadioButton radio = new RadioButton();
                 radio.Name = "Button" + l;
                 radio.CheckedChanged += Radio_CheckedChanged; 

And then when the event is triggered do the following:

    /// <summary>
    /// This will trigger all changes to the CheckedState - even unchecking
    /// </summary>
    private void Radio_CheckedChanged(object sender, EventArgs e)
    {
        RadioButton checkedRadioButton = (RadioButton) sender;//Cast the sender of the event back to RadioButton
        if (checkedRadioButton.Checked)//Only do this when checking - not on unchecking
        {
           MessageBox.Show($"You checked {checkedRadioButton.Name}", "Pressed"); 
        }
    }  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM