我一个GroupBox里面放了很多RadioButton,然后取选中的那个值。比如
public string values="";
if (RadioButton1.Checked)
            {
                values= "差";
            }
            else if (RadioButton2.Checked)
            {
                values= "良好";
            }
            else if (RadioButton3.Checked)
            {
                values= "优秀";
            }else if.........
一共五个RadioButton.现在我的问题是:我有六七个这样的取值,也就是这样的取值方法要写六七次,感觉代码冗余。我现在就是想写个方法,思路应该是在方法里面输入RadioButton的name,然后判断选中的再取值。我现在是有思路但是不知道如何去写,请各位前辈给点建议或者参考代码都行!谢谢

解决方案 »

  1.   

          foreach遍历所有RadioButton控件   判断是否选中、 然后赋值 
      

  2.   

    使用radiobuttonlist <asp:RadioButtonList ID="RadioButtonList2" runat="server">
                <asp:ListItem Text="优秀" Value="优秀"></asp:ListItem>
                <asp:ListItem Text="优秀1" Value="优秀1"></asp:ListItem>
                <asp:ListItem Text="优秀2" Value="优秀2"></asp:ListItem>
                <asp:ListItem Text="优秀3" Value="优秀3"></asp:ListItem>
                <asp:ListItem Text="优秀4" Value="优秀4"></asp:ListItem>
                <asp:ListItem Text="优秀5" Value="优秀5"></asp:ListItem>
                <asp:ListItem Text="优秀6" Value="优秀6"></asp:ListItem>
            </asp:RadioButtonList>
     string value = "";
                for (int i = 0; i < RadioButtonList2.Items.Count; i++)
                {
                    if (RadioButtonList2.Items[i].Selected)
                    {
                        value = RadioButtonList2.Items[i].Value;
                    }
                }
                Response.Write("<script>alert('" + value + "')</script>");
      

  3.   

    我是winform啦,并且是RadioButton只能单选的类!
      

  4.   

    this.RadioButtonList1.Items[this.RadioButtonList1.SelectedIndex].Value
    RadioButtonList1.SelectedValue
      

  5.   


    private void GetRadioButton(GroupBox gb)
            {
                System.Windows.Forms.Control.ControlCollection rbColl = gb.Controls;
                foreach (Control radioButton in rbColl)
                {
                    RadioButton rb = (RadioButton)radioButton;
                    if (rb.Checked)
                    {
                        //操作
                    }
                }
            }
      

  6.   

    用面向对象的思想来解决这个问题太容易了
    条件:窗体Form1中有5个RadioButton(他们必须在同一个容器内),有一个button,一个label
    只要我们选中哪个RadioButton,我们就能获取它的Text值
    在button1事件中我们写
    foreach (Control ctr in this.Controls)
    {
      if(ctr is RadioButton)
      {
         RadioButton ck=ctr as RadioButton;
         if(ck.checked)
         {
            this.lable1.Text=ck.text;
         }
      }
    }
    方便吗,代码少了,看着简洁.
      

  7.   

    将这几个RadioButton放在同一个组里面,遍历组中的选择值!