Radio button selection return in C#

Asked

Viewed 2,085 times

2

Good morning. I have a Groupbox that contains 5 Radiobutton. I have a function where it receives the name of the Groupbox and it returns 1 if any Radiobutton is selected and -1 if no Radiobutton has been selected. But even without any selected Radiobutton, it always returns 1. I wish someone could help me figure out where the error is. Follows the function.

public static int getCheckedRadioButton(Control c)
{
    int i=0;
    try
    {
        Control.ControlCollection cc = c.Controls;
        for (i = 0; i < cc.Count; i++)
        {
           RadioButton rb = cc[i] as RadioButton;
           if (rb.Checked)
           {
              return i;  //retorna o indice do RadioButton selecionado
           }
        }
    }
    catch
    {
        i = -1; // se não tiver nenhum selecionado retorna -1.
    }

    return i;
}
  • is Windows Forms? Webforms?

  • what the return should be if he found a selected item return 1 and -1 to none selected. or index of selected item equal description in code !

  • 1

    Guys. Thank you so much for the answers. All solutions worked. Thanks. José Carlos

2 answers

3

The code always returns 1, when there is none Radiobutton Checked, because there is only one control within the control c. If there were 2 it would return 2, etc.

Note that the i is incremented in the cycle for for each control in c, ended with a value equal to cc.Count.

You must use an auxiliary variable to store the Radiobutton Checked.

Should also ensure that the control is of the type Radiobutton before checking if he is Checked. This will avoid using the block try/catch, which should not be used for such situations.

public static int getCheckedRadioButton(Control c)
{
    int index = -1;
    Control.ControlCollection cc = c.Controls;
    for (i = 0; i < cc.Count; i++)
    {
       if(cc[i] is RadioButton)
       {
           index++;
           RadioButton rb = cc[i] as RadioButton;
           if (rb.Checked)
           {
              return index;  //retorna o indice do RadioButton selecionado
           }
       }
    }
    return -1;
}

It is possible to simplify the code in several ways, among them using foreach:

public static int getCheckedRadioButton(Control c)
{
    //índice do RadioButton selecionado, -1 indica que não há nenhum.
    int index = -1;
    //Controls implementa a interface IEnumerable, podemos usar foreach
    foreach(var control in c.Controls)
    {
       if(control is RadioButton)//Verifica se é um RadioButton
       {
           //Foi encontrado um RadioButton, incrementa o índice
           index++;
           //faz o cast do control para RadioButton e verifica se está selecionado
           if ((RadioButton)control.Checked)
           {
              return index;  //retorna o índice do RadioButton selecionado
           }
       }
    }
    return -1;
}

Using LINQ can be further simplified and directly obtain a reference to Radiobutton selected:

var checkedRadioButton = container.Controls
                             .OfType<RadioButton>()
                             .FirstOrDefault(r => r.Checked);

Where container is the control where the Radiobutton. If there is none selected checkedRadioButton will be null;

  • I was also in doubt, if only to return the element or element 1 for some selected and -1 for none selected. AP does not interact!

  • @Virgilionovic, I had no doubt. What the AP wants is to return the index of the selected or -1 if there is none. The problem is that the code posted on the question is wrong for the reason I pointed out in the answer.

  • So @ramaral what was missing he put the example of this Groupbox, which in the question he says he has Radiobutton if it only has radio button does not need control variable own i for a simple is would already answer his question! but, it’s like I said no user interaction ...

1


In your code, you failed to check whether the Control is of a certain type, is falling in value -1 each time because of different elements of the RadioButton who does not own the property Checked, that is, always giving error: try catch:

If inside that GroupBox only have RadioButton the code below solves your problem by returning the index of the selected object:

The code below should solve this:

public static int GetCheckedRadioButton(Control controls)
{
    int ret = -1;
    for(int i = 0; i < controls.Controls.Count && ret == -1; i++)
    {
        if (controls.Controls[i] is RadioButton)
        {
            if (((RadioButton)controls.Controls[i]).Checked)
            {
                ret = i; // seria o índice que precisa.                        
            }
        }
    }
    return ret;
}

private void BtnVerificar_Click(object sender, EventArgs e)
{
     int result = GetCheckedRadioButton(groupBox1);
     /// continuando ...
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.