【问题标题】:What's the proper way to read which RadioButton is checked in C#? [duplicate]在 C# 中读取哪个 RadioButton 的正确方法是什么? [复制]
【发布时间】:2011-08-08 18:51:27
【问题描述】:

我想知道是否有任何正确方法可以读取从一个 GroupBox 中选中的 RadioButton。到目前为止,我会为每个 GroupBox 创建一些类似的东西。

    private int checkRadioButton() {
        if (radioButtonKwartal1.Checked) {
            return 1;
        } else if (radioButtonKwartal2.Checked) {
            return 2;
        } else if (radioButtonKwartal3.Checked) {
            return 3;
        } else if (radioButtonKwartal4.Checked) {
            return 4;
        }
        return 0;

    }

编辑:有一些很好的答案,但知道按下哪个单选按钮是一回事,但知道附加到它的返回值是第二个。我怎样才能做到这一点?上面的代码让我得到返回值,然后我可以在以后的程序中使用。

【问题讨论】:

标签: c# c#-4.0


【解决方案1】:

你可以使用 LINQ

var checkedButton = container.Controls.OfType<RadioButton>().Where(r => r.IsChecked == true).FirstOrDefault();

这假设您将所有单选按钮直接放在同一个容器中(例如,面板或表单),并且容器中只有一个组。

否则,您可以在每个组的构造函数中创建List&lt;RadioButton&gt;s,然后编写list.FirstOrDefault(r =&gt; r.Checked)

Which Radio button in the group is checked?

【讨论】:

  • 我现在唯一需要知道的是如何知道哪个值分配给了哪个单选按钮? :-) 因为我现在知道选择了第一个单选按钮,但我不知道应该为其分配什么值,所以我需要将1 应用于第一个单选按钮,2 应用于第二个单选按钮等等的方法。
  • @MadBoy:我会这样命名它们,以便我可以将它们的名称子串起来并识别它们的序列号。例如rdButton1、rdButton2 等。名称上的子字符串会告诉您 1、2 等。这有意义吗?
  • 我也在考虑将我需要的价值放入Tag。不知道那个选项是什么所以return Convert.ToInt32(checkedButton.Tag);所以不确定它是否不会破坏任何内置的东西。
  • -1 如果您要复制其他人的答案,您可能应该承认他们的工作并以某种方式构建它。 stackoverflow.com/questions/1797907/…
  • 当然。谢谢,但实际上有一个语法变化。原始语法不正确。那不是本意。已编辑。
【解决方案2】:

您可以使用CheckedChanged 事件来创建您自己的跟踪器。

来自MSDN

void radioButton_CheckedChanged(object sender, EventArgs e)
{
    RadioButton rb = sender as RadioButton;

    if (rb == null)
    {
        MessageBox.Show("Sender is not a RadioButton");
        return;
    }

    // Ensure that the RadioButton.Checked property
    // changed to true.
    if (rb.Checked)
    {
        // Keep track of the selected RadioButton by saving a reference
        // to it.
        selectedrb = rb;
    }
}

您需要创建一个 GroupBoxes 字典或其他东西来存储每个组选定的单选按钮,其中组假定为 rb.Parent

【讨论】:

    【解决方案3】:

    另一种方法是将所有 RadioButtons 连接到单个事件并在单击它们时管理状态。以下代码摘自 MSDN:

    void radioButton_CheckedChanged(object sender, EventArgs e)
    {
        RadioButton rb = sender as RadioButton;
    
        if (rb == null)
        {
            MessageBox.Show("Sender is not a RadioButton");
            return;
        }
    
        // Ensure that the RadioButton.Checked property
        // changed to true.
        if (rb.Checked)
        {
            // Keep track of the selected RadioButton by saving a reference
            // to it.
            selectedrb = rb;
        }
    }
    

    http://msdn.microsoft.com/en-us/library/system.windows.forms.radiobutton.aspx

    【讨论】:

      猜你喜欢
      • 2010-10-14
      • 2020-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-29
      • 1970-01-01
      • 2020-09-14
      相关资源
      最近更新 更多