I have a RadioButtonList which is being populated from a Database, users need to at at least check/select one of the RadioButtons. How can I make sure they check/select the RadioButton? I tried many different ways but no luck, here is my code. I'm also trying to alert them of the uncheck radiobutton.
What I'm trying to do is to validate the RadioButtonList is checked/selected.
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>";
}
instead of doing it on the code behind use an asp.net required field validator:
here is an example:
<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>
on the code behind you can create a blank div and then add text to it on error and you can use the jquery change function to manipulate it further:
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
We can use normal RequiredFieldValidation with not defining InitialValue property
<asp:RadioButtonList runat="server" ID="Radioyesno" RepeatDirection="Horizontal">
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:RadioButtonList>
<asp:RequiredFieldValidator runat="server" ID="RFV123" ValidationGroup="VG1" ControlToValidate="Radioyes" ErrorMessage="PLEASE SELECT YES/NO"/>
it works for me, no complex thinking
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With