我有一个RadioButtonList和一个提交按钮的网页表格。当我单击带有空RadioButtonList值的submit按钮(即没有从RadioButtonList中选择任何内容)时,将得到一个异常:
对象引用未设置为对象实例。
下面是我到目前为止掌握的代码:
protected void Button2_Click1(object sender, EventArgs e)
{
//for qstn 1
con.Open();
if (RadioButtonList1.SelectedValue == null)
{
SqlCommand sqlcmd1 = new SqlCommand("update TEST1 set Your_Answer=NULL where Question='1'", con);
sqlcmd1.ExecuteScalar();
}
else
{
string rb1 = RadioButtonList1.SelectedItem.Text;
SqlCommand cmd1 = new SqlCommand("update TEST1 set Your_Answer='" + rb1 + "' where Question='1'", con);
cmd1.ExecuteScalar();
}
}发布于 2014-04-16 04:52:58
您可以使用SelectedIndex检查是否选择了任何元素,因为SelectedValue不会是空事件,没有选择任何元素。正如MSDN上关于SelectedItem的声明一样,“表示从列表控件中选择的最低索引项的ListItem。默认值为null”,如果SelectedItem为null,则无法访问Text属性并获得异常。
if (RadioButtonList1.SelectedIndex == -1)
{
SqlCommand sqlcmd1 = new SqlCommand("update TEST1 set Your_Answer=NULL where Question='1'", con);
sqlcmd1.ExecuteScalar();
}
else
{
string rb1 = RadioButtonList1.SelectedItem.Text;
SqlCommand cmd1 = new SqlCommand("update TEST1 set Your_Answer='" + rb1 + "' where Question='1'", con);
cmd1.ExecuteScalar();
}}或
您可以使用SelectedItem而不是SelectedValue,就像格兰特温尼所说的那样。
if (RadioButtonList1.SelectedItem == null)https://stackoverflow.com/questions/23100226
复制相似问题