我有一个从数据库中填充的 RadioButtonList,用户至少需要检查/选择其中一个 RadioButton。我怎样才能确保他们检查/选择 RadioButton?我尝试了很多不同的方法但没有运气,这是我的代码。我还试图提醒他们取消选中单选按钮。
我要做的是验证 RadioButtonList 是否被选中/选中。
if (cblstatus.SelectedItem.Value == "1")
{
//Create Category
con.Open();
SqlCommand departament = new SqlCommand("insert into categories(ca_name, ca_number, ca_status, ca_department, ca_date, ca_time, ca_user) " +
"values('" + category.Text + "', '" + number.Text + "', 'Y', '" + catdepartment.SelectedValue + "', '" + date + "', '" + time + "', '" + user + "')", con);
departament.ExecuteNonQuery();
con.Close();
}
else if (cblstatus.SelectedItem.Value == "2")
{
//Create Category
con.Open();
SqlCommand departament = new SqlCommand("insert into categories(ca_name, ca_number, ca_status, ca_department, ca_date, ca_time, ca_user) " +
"values('" + category.Text + "', '" + number.Text + "', 'N', '" + catdepartment.SelectedValue + "', '" + date + "', '" + time + "', '" + user + "')", con);
departament.ExecuteNonQuery();
con.Close();
}
else if (cblstatus. == null)
{
alert.InnerHtml = "<div id=\"warning\" class=\"message warning\">Warning! Please select a department.</div>" +
"<script>" +
"setTimeout(function () { $('#success').fadeOut(); }, 2000);" +
"</script>";
}
最佳答案
不要在后面的代码中使用 asp.net 必填字段验证器:
这是一个例子:
<asp:RadioButtonList runat="server" ID="gender" RepeatDirection="Horizontal" RepeatLayout="Flow" CssClass="labels">
<asp:ListItem Text="Male" Value="Male"></asp:ListItem>
<asp:ListItem Text="Female" Value="Female"></asp:ListItem>
<asp:RequiredFieldValidator runat="server" ID="genderRequired" Display="Dynamic"
ControlToValidate="gender" ErrorMessage="This is an Error"
ValidationGroup="signUp">*</asp:RequiredFieldValidator>
在后面的代码中,您可以创建一个空白 div,然后在出现错误时向其中添加文本,您可以使用 jquery 更改功能进一步操作它:
if (gender.SelectedItem.Value == "Male")
{
//do stuff
}
else if (gender.SelectedItem.Value == "Female")
{
//do stuff
}
else
{
errorDiv.InnerText = "Error Messeage";
}
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.requiredfieldvalidator.aspx
关于c# - 如何验证 RadioButtonList 是否在 C# 中检查/选择它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8766324/