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
;
is Windows Forms? Webforms?
– novic
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 !
– novic
Guys. Thank you so much for the answers. All solutions worked. Thanks. José Carlos
– Jose Carlos Taveira