'Insert radio button selected value into database
I am building a C# Windows application with 2 radio buttons for gender. I'm using a simple insert query to insert data in the database.
Can anyone help me with inserting the selected radio button value to the database? I am using 2 radio buttons, not a radio button list.
For the moment my query is as follows:
Class1.ABC("insert into emp(code,names,m_name,desgnation,gender)
values ('" + textBox1.Text + "','" +
textBox2.Text + "','" +
textBox3.Text + "','" +
textBox4.Text + "','" +
textBox5.Text + "','" +
radioButton1.Checked+"' )");
Solution 1:[1]
You can check checked
property and set value as per your requirement.
Class1.ABC("insert into emp(code,names,m_name,desgnation,gender)
values ('" + textBox1.Text + "',
'" + textBox2.Text + "',
'" + textBox3.Text + "',
'" + textBox4.Text + "',
'" + textBox5.Text + "',
'"+ radioButton1.Checked ? "Male" : "Female" +"' )");
Note : Use parameterized queries
Solution 2:[2]
Simply Inser RadioButton Text
Like this
Class1.ABC("insert into emp(code,names,m_name,desgnation,gender)
values ('" + textBox1.Text + "','" +
textBox2.Text + "','" +
textBox3.Text + "','" +
textBox4.Text + "','" +
textBox5.Text + "','" +
radioButton1.Text + "' )");
Solution 3:[3]
private string RadioButtonText()
{
if (radioButton1.Checked)
{
return radioButton1.Text;
}
else
{
return radioButton2.Text;
}
}
Solution 4:[4]
You could create a method, pass a list of RadioButton
s to the method and perform validation and eventually retrieve the Text
property inside this method. This allows you to extend the functionality in the future easier when needed, keeps your original code clean (no strange inline validation/checks).
I'd do something like:
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 }) + "' )");
}
Solution 5:[5]
You can Try this:
Add a Label, make it invisible.get the checked radiobutton's value into the label. Now in sql statement, use label's value(which is in fact the checked radiobutton's value) to insert into 'gender'. I recommend this only if you are a beginner & anyhow want to get the program running.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sameer |
Solution 2 | Vignesh Kumar A |
Solution 3 | Termininja |
Solution 4 | Jevgeni Geurtsen |
Solution 5 |