gpt4 book ai didi

c# - RadioButtonList 空值

转载 作者:太空宇宙 更新时间:2023-11-03 10:46:42 25 4
gpt4 key购买 nike

我在 Web 表单上有一个 RadioButtonList 和一个提交按钮。当我单击具有空 RadioButtonList 值的提交按钮时,即没有从 RadioButtonList 中选择任何内容,我得到一个异常:

Object reference not set to an instance of object.

这是我目前的代码:

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();
}
}

最佳答案

您可以使用 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();
}}

如 Grant Winney 所述,您可以在条件中使用 SelectedItem 而不是 SelectedValue。

if (RadioButtonList1.SelectedItem == null)

关于c# - RadioButtonList 空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23100226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com