哪个单选按钮组中被选中?单选、组中、按钮

2023-09-02 10:22:05 作者:≒赱ζц斯文

使用的WinForms;有没有更好的方法来找到检查单选按钮为一组?在我看来,这低于code没有必要。当您检查一个不同的单选按钮,然后它知道要取消......哪一个,所以应该知道哪些检查。我该如何将这些信息没有做大量的if语句(或交换机)。

 单选RB = NULL;

     如果(m_RadioButton1.Checked ==真)
     {
        RB = m_RadioButton1;
     }
     否则,如果(m_RadioButton2.Checked ==真)
     {
        RB = m_RadioButton2;
     }
     否则,如果(m_RadioButton3.Checked ==真)
     {
        RB = m_RadioButton3;
     }
 

解决方案

您可以使用LINQ:

  VAR checkedButton = container.Controls.OfType<单选>()
                                      .FirstOrDefault相关(r => r.Checked);
 
jQuery判断关于单选按钮组的选中

请注意,这要求所有的单选按钮在相同的容器(例如,盘或表)可以直接,而且只有一个组中的容器中。如果不是的话,你可以让名单,其中,单选> 在你的构造函数为每个组,然后写 list.FirstOrDefault(R =&GT ; r.Checked)

Using WinForms; Is there a better way to find the checked RadioButton for a group? It seems to me that the code below should not be necessary. When you check a different RadioButton then it knows which one to uncheck… so it should know which is checked. How do I pull that information without doing a lot of if statements (or a switch).

     RadioButton rb = null;

     if (m_RadioButton1.Checked == true)
     {
        rb = m_RadioButton1;
     }
     else if (m_RadioButton2.Checked == true)
     {
        rb = m_RadioButton2;
     }
     else if (m_RadioButton3.Checked == true)
     {
        rb = m_RadioButton3;
     }

解决方案

You could use LINQ:

var checkedButton = container.Controls.OfType<RadioButton>()
                                      .FirstOrDefault(r => r.Checked);

Note that this requires that all of the radio buttons be directly in the same container (eg, Panel or Form), and that there is only one group in the container. If that is not the case, you could make List<RadioButton>s in your constructor for each group, then write list.FirstOrDefault(r => r.Checked).