【问题标题】:c# Geting values of multiple group of radiobuttonsc#获取多组单选按钮的值
【发布时间】:2015-06-15 10:57:28
【问题描述】:


我有一个包含多个 Groups 的 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 而不是检查每个组中的每个 Radio Button 是否已选中? 请看我的形象..了解更多。 请帮助大家,并提前感谢您。

【问题讨论】:

  • 使用谷歌搜索如何获取 RadioButton Group 的值...

标签: c# radio-button


【解决方案1】:

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

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?

【讨论】:

  • 谢谢你。这是 c# (cSharp) 的代码吗?我不能使用第一行: var radioButtons = new List();关键字“ var ”给了我错误。
  • 是的,它是 c#。您总是可以更明确地做到List&lt;RadioButton&gt; radioButton = new List&lt;RadioButton&gt;(); var 只是编译器的快捷方式。
猜你喜欢
  • 2017-02-06
  • 1970-01-01
  • 2011-03-28
  • 1970-01-01
  • 2013-10-14
  • 1970-01-01
  • 2016-05-08
  • 2013-09-04
  • 2014-12-05
相关资源
最近更新 更多