c# - 如何验证 RadioButtonList 是否在 C# 中检查/选择它?

标签 c# asp.net .net

我有一个从数据库中填充的 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/

相关文章:

c# - 如何创建返回 void 的匿名方法?

c# - 如何使用 C# 安全地关闭所有正在运行的应用程序

c# - 创建一个需要管理员权限的 C# 应用程序

c# - asp.net C# Request.QueryString ["sms"] + 符号

.net - 如何禁止引用 .NET DLL 类库

javascript - 如何启用asp :LinkButton on client side

c# - 临时调试版本和最终应用程序版本

c# - ASP NET MVC C# - .Model 是一个属性,但它像一个类型一样使用

c# - ASP.NET Core Web 应用程序 - 如何上传大文件

.net - CorFlags.exe、System.Data.SQLite.dll 和 BadImageFormatException