C#中实现RadioButtonList

制作时间:2009-9-10 8:00-9:30
制作地点:北大青鸟公共机房

目的:
  1.用软编码的方式,在一组单选按钮中,找到选中的单选按钮的Text

   private void btnCheck_Click(object sender, EventArgs e)
        {
            bool flag = false;//如果为true表示有被选中的单选按扭
            string option = string.Empty;//接受被选中的单选按扭的Text
            //循环遍历分组框中所有的单选按扭
            //如果有被选中的,则得到单选按扭的Text
            foreach (Control control in grpRadios.Controls)
            {
                RadioButton radio = control as RadioButton;
                if (radio != null && radio.Checked)
                {
                    flag = true;
                    option = radio.Text;
                    MessageBox.Show(option);
                }
            }
            if (!flag)
            {
                MessageBox.Show("请选择一个单选按扭!","提示",MessageBoxButtons.OK);
                return;
            }
        }
    2.可以专门用一个分组框 盛放单选按钮,则遍历的时候直接Radio,而不用类型转换了
    private void btnCheck_Click(object sender, EventArgs e)
        {
            bool flag = false;
            string option = string.Empty;
            foreach (Radio radio in grpRadios.Controls)//这里用Radio
            {

                if (radio != null && radio.Checked)
                {
                    flag = true;
                    option = radio.Text;
                    MessageBox.Show(option);
                }
            }
            if (!flag)
            {
                MessageBox.Show("请选择一个单选按扭!","提示",MessageBoxButtons.OK);
                return;
            }
        }
    3.进一步简化,不需要用flag来标识是否选中单选按钮,直接用message判断
        private string GetRadioValueOfGroupBox(Control.ControlCollection controls)
        {
            string message = string.Empty;
            foreach (RadioButton radio in controls)
            {
                if (radio != null && radio.Checked)
                {
                    message = radio.Text;
                }
            }
            return message;
        }

你可能感兴趣的:(RadioButton)