Not sure how to get value of radiobuttons created in C# code

87 Views Asked by At

I'm trying to develop a program which writes metadata in a logfile. I've created some radiobuttons dynamically(from xml file) into the form, but im not sure how to get their values and write them into a logfile.

Code to create radiobuttons:

foreach (XmlNode node in nodes)
{
    count += 1;
    if (count < 4)
    {
         int heightRadioButtons = 0;
         WidthPanelsRow1 += 155;
         Panel panel = new Panel();
         panel.Size = new Size(140, 200);
         panel.Location = new Point(WidthPanelsRow1, heightPanelsRow1);
         panel.BackColor = Color.LightGray;

         Label lbl = new Label();
         lbl.Text = node["Titel"].InnerText;
         lbl.Location = new Point(0, 0);
         lbl.Font = font1;
         panel.Controls.Add(lbl);

         int counterLastRadioButton = 0;
         XmlNodeList waardeNodes = node.SelectNodes("Waardes");
         foreach (XmlNode wNode in waardeNodes)
         {
             counterLastRadioButton += 1;
             heightRadioButtons += 20;
             RadioButton rb = new RadioButton();
             rb.Text = wNode.InnerText;
             rb.Location = new Point(5, heightRadioButtons);
             rb.Name = "rb" + count.ToString();
             if (waardeNodes.Count - 1 < counterLastRadioButton)
             {
                  rb.Checked = true;
             }
             panel.Controls.Add(rb);
         }
         this.Controls.Add(panel);
    }
}

In the current xml file, 9 radiobutton options will be created. What I'm trying to reach is that for each 9 "Titel" I get the selected "Waardes" in another method.

UPDATE

I managed to get the last value of 1 radiobutton group by doing this:

for (int i = 1; i < radioButtonCounter; i++)
{
    RadioButton rb = this.Controls.Find("rb"+i.ToString(), true).LastOrDefault() as RadioButton;
    MessageBox.Show(rb.Text);
}

This will only give me the last element of a group, how can i get the entire group and see which one is checked?

Thanks

1

There are 1 best solutions below

0
Niels On

Fixed it, see code of solution below:

var panels = Controls.OfType<Panel>().ToList();
foreach (Panel p in panels)
{
     var selectedRadioButton = p.Controls.OfType<RadioButton>().FirstOrDefault(rb => rb.Checked);
     if (selectedRadioButton != null)
     {
          MessageBox.Show($"{p.Name}.{selectedRadioButton.Text}");
     }
}