简体   繁体   English

识别使用枚举作为值检查哪个单选按钮

[英]recognize which radio button is checked using enum as value

I'm struggling with WinForms.我正在努力使用 WinForms。 I have a GroupBox which wraps three RadioButton s.我有一个包含三个RadioButtonGroupBox I added them using the design view and inside the constructor I tag every button to corresponding enum value like我使用设计视图添加了它们,并在构造函数中将每个按钮标记为相应的枚举值,例如

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

Inside my class I have property property of type Dictionary which uses this enum as a key, so I want when the user clicks on winform button to recognize which radio button is checked and to assign to that dictionary.在我的班级中,我有一个Dictionary类型的属性属性,它使用这个枚举作为键,所以我希望当用户点击 winform 按钮时识别哪个单选按钮被选中并分配给该字典。

I've found how to fetch checked option我找到了如何获取选中的选项

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

Do I need to use switch statement to recognize which Enum is checked or is there some better way?我是否需要使用 switch 语句来识别检查了哪个 Enum 或者有更好的方法吗?

You get the UserChoiceEnum by:您可以通过以下方式获得 UserChoiceEnum:

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

If you set Tag you can simply get it back whenever you need.如果您设置了Tag您可以在需要时简单地取回它。 Note that you need to cast it to original type.请注意,您需要将其转换为原始类型。 Something like:就像是:

var choiceAsEnum = (UserChoiceEnum)choice.Tag;

created enum :创建的枚举:

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

Then use SelectedIndexChanged event of radioGroup control.然后使用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;
      }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM