【问题标题】:Not sure how to get value of radiobuttons created in C# code不确定如何获取在 C# 代码中创建的单选按钮的值
【发布时间】:2018-03-27 14:24:51
【问题描述】:

我正在尝试开发一个将元数据写入日志文件的程序。 我已经在表单中动态创建了一些单选按钮(来自 xml 文件),但我不确定如何获取它们的值并将它们写入日志文件。

创建单选按钮的代码:

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);
    }
}

在当前的 xml 文件中,将创建 9 个单选按钮选项。我想要达到的是,对于每 9 个“Titel”,我会以另一种方法获得选定的“Waardes”。

更新

通过这样做,我设法获得了 1 个单选按钮组的最后一个值:

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

这只会给我一个组的最后一个元素,我怎样才能得到整个组并查看哪个被选中?

谢谢

【问题讨论】:

  • 一个组中的所有单选按钮可以汇总为一个值来存储。因此,您只需为每个单选按钮组存储一个值。事实上,每个组的行为就像单个ComboBox 或单选ListBox。为方便起见,请查看此自定义 Windows Forms RadioButtonList

标签: c# winforms radio-button selected logfiles


【解决方案1】:

已修复,见下方解决方案代码:

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}");
     }
}

【讨论】:

    猜你喜欢
    • 2016-09-22
    • 2017-05-15
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多