将单选按钮选定的值插入数据库

新手上路,请多包涵

我正在构建一个带有 2 个性别单选按钮的 C# Windows 应用程序。我正在使用一个简单的插入查询在数据库中插入数据。

谁能帮我将选定的单选按钮值插入数据库?我正在使用 2 个单选按钮,而不是单选按钮列表。

目前我的查询如下:

 Class1.ABC("insert into emp(code,names,m_name,desgnation,gender)
                        values ('" + textBox1.Text + "','" +
                                     textBox2.Text + "','" +
                                     textBox3.Text + "','" +
                                     textBox4.Text + "','" +
                                     textBox5.Text + "','" +
                                     radioButton1.Checked+"' )");

原文由 Srima 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 496
1 个回答

您可以创建一个方法,将 RadioButton 的列表传递给该方法并执行验证并最终检索该方法内的 Text 属性。这允许您在将来需要时更轻松地扩展功能,保持原始代码干净(没有奇怪的内联验证/检查)。

我会做类似的事情:

 public string GetSelectedRadioButtonText(RadioButton[] radioButtons)
{
    // possible additional checks: check multiple selected, check if at least one is selected and generate more descriptive exception.

    // works for above cases, but throws a generic InvalidOperationException if it fails
    return radioButtons.Single(r => r.Checked).Text;
}

public void YourMethod()
{
    Class1.ABC("insert into emp(code,names,m_name,desgnation,gender)
                values('" + textBox1.Text + "', '" +
                             textBox2.Text + "','" +
                             textBox3.Text + "','" +
                             textBox4.Text + "','" +
                             textBox5.Text + "','" +
                             this.GetSelectedRadioButtonText(new[] { rb1, rb2 }) + "' )");
}

原文由 Jevgeni Geurtsen 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进