Return radiobutton selection in C #

2

Good morning. I have a GroupBox that contains 5 RadioButton. I have a function where it gets the name of the GroupBox and it returns 1 if some RadioButton is selected and -1 if no RadioButton has been selected. But even without a RadioButton selected, it always returns 1. I wish someone could help me figure out where the error is. Follow 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;
}
    
asked by anonymous 13.10.2016 / 15:17

2 answers

1

In your code, you have checked to see if Control is of a certain type, it is falling by -1 every time because of elements other than RadioButton " that does not have property Checked , that is, always giving error: try catch :

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

The code below should resolve 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 ...
}
    
13.10.2016 / 15:30
3

The code always returns 1, when there is no RadioButton Checked , because there is only one control inside the c control. If there were 2 return 2, etc.

Notice that the i is incremented in the for loop for each control in c , ending with a value equal to cc.Count .

You should use an auxiliary variable to store the index of the RadioButton Checked .

You should also ensure that the control is of type RadioButton before checking that it is Checked . This will prevent the use of the try/catch block, which should not be used for this type of situation.

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;
}

You can simplify your code in a number of ways, including 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 streamlined and get a direct reference to the selected RadioButton :

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

Where container is the control where the RadioButton are. If there is no selected checkedRadioButton will be null ;

    
13.10.2016 / 16:12