Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the proper way to read which RadioButton is checked in C#? [duplicate]

Tags:

c#

c#-4.0

I was wondering if there's any proper way of reading RadioButton that's checked from one GroupBox. So far I would create something along this lines per each GroupBox.

    private int checkRadioButton() {
        if (radioButtonKwartal1.Checked) {
            return 1;
        } else if (radioButtonKwartal2.Checked) {
            return 2;
        } else if (radioButtonKwartal3.Checked) {
            return 3;
        } else if (radioButtonKwartal4.Checked) {
            return 4;
        }
        return 0;

    }

Edit: there are some preety good answers but knowing which radioButton is pressed is one thing, but knowing the return value attached to it is 2nd. How can I achieve that? The code above lets me get return values which then I can use later in a program.

like image 679
MadBoy Avatar asked Apr 19 '11 15:04

MadBoy


People also ask

How do you check whether a RadioButton is selected or not in jQuery?

We can check the status of a radio button by using the :checked jQuery selector together with the jQuery function is . For example: $('#el').is(':checked') . It is exactly the same method we use to check when a checkbox is checked using jQuery.

What are radio buttons and check boxes?

Checkboxes and radio buttons are elements for making selections. Checkboxes allow the user to choose items from a fixed number of alternatives, while radio buttons allow the user to choose exactly one item from a list of several predefined alternatives.

Should radio buttons be selected by default?

Always Offer a Default SelectionIn case of radio buttons this means that radio buttons should always have exactly one option pre-selected. Select the safest and most secure option (to prevent data loss).


1 Answers

You can use LINQ

var checkedButton = container.Controls.OfType<RadioButton>().Where(r => r.IsChecked == true).FirstOrDefault();

This assumes that you have all of the radio buttons be directly in the same container (eg, Panel or Form), and that there is only one group in the container.

Otherwise, you could make List<RadioButton>s in your constructor for each group, then write list.FirstOrDefault(r => r.Checked)

Which Radio button in the group is checked?

like image 94
Priyank Avatar answered Nov 09 '22 20:11

Priyank