c#获取多组radiobutton的值

时间:2015-04-09 21:22:56

标签: c# radio-button


我是一个包含多个组的C#Windows窗体应用程序,每个组都包含一些单选按钮。 我想将每个组的值插入到我的ACCESS数据库表中。  我试图从像

这样的每个功能返回
private void Get_Gender(RadioButton GenderButton)
        {
            if (GenderButton.Checked)
            {
                Return GenderButton.Text;
            }
        }

private void Get_Age(RadioButton AgeButton)
        {
            if (AgeButton.Checked)
            {
                Return AgeButton.Text;
            }
        }
private void Get_Interest(RadioButton InterestButton)
        {
            if (InterestButton.Checked)
            {
                Return InterestButton.Text;
            }
        }

然后尝试从

等函数中选择它们
String Gender = Get_Gender(I don’t know what to put here);
String Age= Get_Age(I don’t know what to put here);
String Interestr = Get_Interest(I don’t know what to put here);

然后创建连接..(这没问题)

OleDbConnection con = new OleDbConnection();
Command cmd = new oleDbCommand(“INSERT into tbl (Age, Gender, Interest) “+”values(@age, @gend, @int”, con);  

查询不会有问题,

 but values of those three groups.
Getting those values (@age, @gend, @int”, con); 
让我发疯... 是否有一种简单的方法可以通过代码获取已检查的RadioButton,而不是检查每个组中的每个单选按钮是否被检查? 请看我的形象......了解更多。 请帮助你们,并提前感谢你们。

1 个答案:

答案 0 :(得分:0)

您可以传入一个单选按钮对象列表,循环遍历它们,直到您获得第一个选择。主要问题是它们是不同的对象,即使它们是分组的并且只能选择一个。

var radioButtons = new List<RadioButton>();
radioButton.Add(Form.rbGenderMale);
radioButton.Add(Form.rbGenderFemale);

然后你的Get_Gender方法就像

private void Get_Gender(List<RadioButton> genderButtons)
{
    foreach (var genderButton in genderButtons)
    {
        if (genderButton.Checked)
        {
            return genderButton.Text;
        }
     }
 }

如果您正在使用动态单选按钮或者不关心反射效果,但想要在不更改代码的情况下向表单组添加新的单选按钮,那么请查看 How to get a checked radio button in a groupbox?