1

enter image description here enter image description here

This is all the code:

private void button1_Click(object sender, EventArgs e)
{
    foreach (Control control in groupBox1.Controls)
    {
        MessageBox.Show(control.ToString());
    }
}

I only want to get the true value But there is no Checked. How can I get the true value? How can I get each index?

  • 1
    what is "the true value"? What result do you **expect** and what do you **get actually**? – MakePeaceGreatAgain Apr 15 '21 at 13:42
  • Try casting it to a radio. The base Control class doesn't have a checked property. – Crowcoder Apr 15 '21 at 13:42
  • Cast it to RadioButton first, your MessageBox already states what type of control it is – Tomas Chabada Apr 15 '21 at 13:43
  • Control is just controle it can be anything. It cant be checked or unchecked. You should filter to get only the RadioButton. With the Type radio button – Self Apr 15 '21 at 13:44
  • @HimBromBeere: `control.ToString()` contains the text shown in the screen shot, including the "Checked" value (which happens to be `True` in the example). They want that checked value only, but can't find the Checked property (because the control has not been cast yet). Easiest solution is probably `groupBox1.Controls.OfType()`, but I'll let someone else write that down and collect the rep. :-) – Heinzi Apr 15 '21 at 13:44
  • You need ot be able to enumerate through the radio buttons in the group box. Sometimes I use a List. Searching for the radio buttons is slow. – jdweng Apr 15 '21 at 13:45
  • Does this answer your question? [Which Radio button in the group is checked?](https://stackoverflow.com/questions/1797907/which-radio-button-in-the-group-is-checked) – Self Apr 15 '21 at 13:48
  • And Vb version https://stackoverflow.com/questions/6466952/how-to-get-a-checked-radio-button-in-a-groupbox – Self Apr 15 '21 at 13:48

1 Answers1

5

Right now, you have all controls, which is why they are of type control and you don't know what they are at compile-time.

Make sure you only get those of type RadioButton:

private void button1_Click(object sender, EventArgs e)
{
    foreach (RadioButton radioButton in groupBox1.Controls.OfType<RadioButton>())
    {
         MessageBox.Show(radioButton.Checked.ToString());
    }
}
nvoigt
  • 75,013
  • 26
  • 93
  • 142