sham
sham

Reputation: 1356

Detecting which radio button of many was checked using C# & XAML

In Android/Java there is a RadioGroup object which can contain many RadioButtons. RadioGroup also has an OnChanged event which I can listen to and then ask it which RadioButton is now selected (and then get that selected radio buttons Id).

Is there a corresponding way to achieve the same thing in C#? It appears I need to respond to the Checked event for every RadioButton (although they could go to the same event handler), but then in the event handler I need to iterate through every RadioButton to see if it was checked? This is a lot of code if I have many (e.g. 20) RadioButton. Is there an easier way?

Upvotes: 1

Views: 820

Answers (2)

keyboardP
keyboardP

Reputation: 69372

You can assign a property to identify the control such as the Tag property or the Name property. You then attempt to cast the sender in the event handler to a CheckBox type and retrieve the identifying property.

private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
    CheckBox cb = sender as CheckBox;

    if(cb != null)
    {
        string cbName = cb.Name; 
    }
}

By using as instead of an explicit cast ((CheckBox)sender), you avoid throwing an exception should the cast not be valid. That is an unlikely scenario in this case if only CheckBoxes are assigned this event handler but it's good practice in other cases, unless you need to throw an exception for whatever reason.

Upvotes: 2

Normally in windows event handlers there is a sender parameter which can be cast to the appropriate control type that raised the event ... eg.

private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
    CheckBox chk = (CheckBox)sender;
}

Now you know explicitly which CheckBox was checked, at the time the checked event occured.

So in your case, you would hook the same event handler up to all the CheckBoxes, and then identify the newly checked CheckBox with the chk variable.

Upvotes: 1

Related Questions