1.使用RadioButton
核心思想:if (RadioButton1.Checked) 判断选中了哪个按钮,再硬编码sql语句,存储0还是1,这种方式不推荐使用,推荐用RadioButtonList
<asp:RadioButton ID="RadioButton1" runat="server" GroupName="sex" Text="男"/>
<asp:RadioButton ID="RadioButton2" runat="server" GroupName="sex" Text="女"/><br />
<asp:Button ID="Button1" runat="server" Text="提交" OnClick="Button1_Click" />
protected void Button1_Click(object sender, EventArgs e)
{
//创建数据库连接对象
String s = "server=DESKTOP-065E9N6;uid=sa;pwd=123456;database=student";
SqlConnection con = new SqlConnection(s);
con.Open();
int res = 0;
if (con.State == ConnectionState.Open)
{
Label1.Text = "连接成功";
//执行sql语句
//String insertData = "Insert into stu values ('黄志文','001',1)";
if (RadioButton1.Checked)
{
String insertData = "Insert into stu values ('" + TextBox1.Text + "','" + TextBox2.Text + "',1)";
SqlCommand cmd = new SqlCommand(insertData, con);
//执行
res = cmd.ExecuteNonQuery();
}
if (RadioButton2.Checked)
{
String insertData = "Insert into stu values ('" + TextBox1.Text + "','" + TextBox2.Text + "',0 )";
SqlCommand cmd = new SqlCommand(insertData, con);
//执行
res = cmd.ExecuteNonQuery();
}
if (res > 0)
{
Label2.Text = "添加数据成功";
}
else
{
Label2.Text = "添加数据失败,请查看sql语句是否正确";
}
}
else
{
Label1.Text = "连接失败";
}
}
2.使用RadioButtonList
核心思想:String rb=RadioButtonList1.SelectedItem.Value;
获取单选按钮ListItem的value值,再写到sql语句中
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
<asp:ListItem value="1">男</asp:ListItem>
<asp:ListItem value="0">女</asp:ListItem>
</asp:RadioButtonList>
<asp:Button ID="Button1" runat="server" Text="提交" OnClick="Button1_Click" />
protected void Button1_Click(object sender, EventArgs e)
{
//创建数据库连接对象
String s = "server=DESKTOP-065E9N6;uid=sa;pwd=123456;database=student";
SqlConnection con = new SqlConnection(s);
con.Open();
int res = 0;
if (con.State == ConnectionState.Open)
{
Label1.Text = "连接成功";
String rb=RadioButtonList1.SelectedItem.Value;
String insertData = "Insert into stu values ('" + TextBox1.Text + "','" + TextBox2.Text + "',"+rb+ ")";
SqlCommand cmd = new SqlCommand(insertData, con);
//执行
res = cmd.ExecuteNonQuery();
if (res > 0)
{
Label2.Text = "添加数据成功";
}
else
{
Label2.Text = "添加数据失败,请查看sql语句是否正确";
}
}
else
{
Label1.Text = "连接失败";
}
}
}