-2

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

Joshua
  • 40,822
  • 8
  • 72
  • 132
Niels
  • 95
  • 2
  • 9
  • All radio buttons in a group can be summarized to a single value to store. So you need to store just a single value per radio button group. In fact each group acts like a single `ComboBox` or single-select `ListBox`. To make it easier, take a look at this custom [Windows Forms `RadioButtonList`](https://stackoverflow.com/a/41355419/3110834). – Reza Aghaei Oct 16 '17 at 06:44

1 Answers1

0

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}");
     }
}
Niels
  • 95
  • 2
  • 9