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
;