【问题标题】:recognize which radio button is checked using enum as value识别使用枚举作为值检查了哪个单选按钮
【发布时间】:2013-07-16 22:40:22
【问题描述】:

我正在为 WinForms 苦苦挣扎。我有一个GroupBox,它包含三个RadioButtons。我使用设计视图添加它们,并在构造函数中将每个按钮标记为相应的枚举值,例如

public MyApp()
{
   radioBtnBasic.Tag = UserChoiceEnum.Basic;
   radioBtnLite.Tag = UserChoiceEnum.Lite;
   radioBtnStandard.Tag = UserChoiceEnum.Standard;
}

在我的类中,我有 Dictionary 类型的属性属性,它使用此枚举作为键,所以我希望当用户单击 winform 按钮时识别选中了哪个单选按钮并分配给该字典。

我找到了如何获取选中的选项

var choice = grpBox1.Controls.OfType<RadioButton>().FirstOrDefault(x => x.Checked);

我需要使用 switch 语句来识别检查了哪个 Enum 还是有更好的方法?

【问题讨论】:

标签: c# .net winforms enums radio-button


【解决方案1】:

您通过以下方式获得 UserChoiceEnum:

RadioButton choice = grpBox1.Controls.OfType<RadioButton>().FirstOrDefault(x => x.Checked);
UserChoiceEnum userChoice = (UserChoiceEnum)choice.Tag;

【讨论】:

  • 根据用户的选择将一个单选按钮设置为选中的另一面是:grpBox1.Controls.OfType&lt;RadioButton&gt;().FirstOrDefault(x =&gt; (int)x.Tag == usersChoice).Checked = true;
【解决方案2】:

如果您设置了Tag,您可以随时取回它。请注意,您需要将其转换为原始类型。比如:

var choiceAsEnum = (UserChoiceEnum)choice.Tag;

【讨论】:

    【解决方案3】:

    创建枚举:

    public enum SearchType
    {
        ReferenceData = 0,
        Trade = 1,
    }
    

    然后使用radioGroup控制的SelectedIndexChanged事件。

    private void RadioTypes_SelectedIndexChanged(object sender, EventArgs e)
    {
          if (this.RadioTypes.SelectedIndex < 0) return;
          SearchType n = (SearchType)this.RadioTypes.SelectedIndex;
    
          switch (n)
          {
               case SearchType.ReferenceData:
               break;
    
               case SearchType.Trade:
               break;
          }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-17
      • 2012-08-30
      • 1970-01-01
      • 2022-12-30
      • 2017-03-29
      • 1970-01-01
      • 1970-01-01
      • 2021-02-22
      相关资源
      最近更新 更多