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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8766324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 04:21:26  来源:igfitidea点击:

How to validate if a RadioButtonList is check/select it in C#?

c#asp.net.net

提问by jorame

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.

我有一个从数据库填充的 RadioButtonList,用户至少需要检查/选择 RadioButtons 之一。我如何确保他们检查/选择 RadioButton?我尝试了很多不同的方法,但没有运气,这是我的代码。我还试图提醒他们取消选中单选按钮。

What I'm trying to do is to validate the RadioButtonList is checked/selected.

我想要做的是验证 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>";
    }

回答by Wahtever

instead of doing it on the code behind use an asp.net required field validator:

而不是在后面的代码上使用 asp.net 必需的字段验证器:

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:

在后面的代码中,您可以创建一个空白 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

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.requiredfieldvalidator.aspx

回答by Syed Mohamed

We can use normal RequiredFieldValidation with not defining InitialValue property

我们可以使用普通的 RequiredFieldValidation 而不定义 InitialValue 属性

<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

它对我有用,没有复杂的想法

回答by helavin4ik

.aspx :

.aspx :

<asp:RadioButtonList ID="rbAny" runat="server" >
 <asp:ListItem Value="rb1" Text="something1"></asp:ListItem>
 <asp:ListItem Value="rb2" Text="something2"></asp:ListItem>
 <asp:ListItem Value="rb3" Text="something3"></asp:ListItem>
</asp:RadioButtonList>

.aspx.cs :

add/insert values in ViewState(for example by clicking a buttons):

.aspx.cs :

在 ViewState 中添加/插入值(例如通过单击按钮):

protected void btnSend_Click(object sender, EventArgs e)
{
    foreach (ListItem r in rbAny.Items) 
        if (r.Selected) ViewState["anyValue"] = r.Text;
}

read value from ViewState:

从 ViewState 读取值:

protected void btnShow_Click(object sender, EventArgs e)
{
    StringBuilder str = new StringBuilder();
    str.Append("anyValue: " + ViewState["anyValue"]);
    someLabel.Text = str.ToString();
}

回答by Vijay Kumbhoje

Can use this approach but totally code behind

可以使用这种方法,但完全代码落后

 public bool ValidateRadioButtonList()
{
    bool rbchecked= false;
    for (int i = 0; i < RadioButtonList1.Items.Count - 1; i++)
    {
        if (RadioButtonList1.Items[i].Selected==true)
        {
            rbchecked = true;
        }
    }
    if (rbchecked == true)
    {
        lblError.Text = string.Empty;
        return true;
    }
    else
    {
        lblError.Text = "Please select RadioButton!";
        return false;
    }
}

回答by John

Imports System.IO
Imports System.Text
Imports System


Public Class WebForm1
    Inherits System.Web.UI.Page



    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub

    'Protected Sub Calendar1_SelectionChanged(sender As Object, e As EventArgs)

    '    TextBox1.Text = Calendar1.SelectedDate.ToShortDateString()
    '    Calendar1.Visible = False












    'End Sub

    'Protected Sub LinkButton1_Click(sender As Object, e As EventArgs)
    '    'Calendar1.Visible = True


    'End Sub

    'Protected Sub LinkButton2_Click(sender As Object, e As EventArgs)
    '    Calendar2.Visible = True
    'End Sub

    'Protected Sub Calendar2_SelectionChanged(sender As Object, e As EventArgs)
    '    TextBox2.Text = Calendar2.SelectedDate.ToShortDateString()
    '    Calendar2.Visible = False
    'End Sub

    Public Sub DownloadCSV()
        Dim csvPath1 As String = "D:\CSVFile1.csv"

        'Download and read all Text within the uploaded Text file.
        Dim csvContentStr1 As String = File.ReadAllText(csvPath1)

        Dim split As String() = csvContentStr1.Split(","c)

        'Here you can see the output as CSV content.
        'Response.Write(csvContentStr)
    End Sub


    Public Sub UploadCSV()
        Dim csvContent As New StringBuilder()

        DownloadCSV()

        Dim dt1 As DateTime = Convert.ToDateTime(TextBox1.Text)
        Dim dt2 As DateTime = Convert.ToDateTime(TextBox2.Text)
        Dim dt3 As TimeSpan = dt2.Subtract(dt1)
        Dim NoOfDays As Integer = dt3.Days + 1
        'TextBox3.Text = NoOfDays.ToString

        Dim index As DateTime = Convert.ToDateTime(TextBox1.Text)
        While index <= Convert.ToDateTime(TextBox2.Text)
            If index.DayOfWeek = DayOfWeek.Saturday OrElse index.DayOfWeek = DayOfWeek.Sunday Then
                NoOfDays = NoOfDays - 1
            End If
            index = index.AddDays(1)

        End While

        Dim a1 As String = TextBox1.ToString()
        Dim b1 As String = TextBox2.ToString()
        Dim c1 As String = RadioButtonList1.Text.ToString()
        Dim d1 As String = TextBox3.ToString()

        Dim z1 As String = TextBox1.Text + "," + TextBox2.Text + "," + RadioButtonList1.Text + "," + TextBox3.Text + "," + NoOfDays.ToString

        'csvContent.AppendLine("From Date,To Date,Laeve Type,Reason")
        csvContent.AppendLine(z1)

        Dim csvPath As String = "D:\CSVFile2.csv"

        ' Save or upload CSV format File (.csv)
        File.AppendAllText(csvPath, csvContent.ToString())
    End Sub


    Protected Sub Button1_Click(sender As Object, e As EventArgs)








        If Page.IsValid Then
            Dim a1 As String = TextBox1.ToString()
            Dim b1 As String = TextBox2.ToString()
            Dim c1 As String = RadioButtonList1.Text.ToString()
            Dim d1 As String = TextBox3.ToString()





            UploadCSV()
            DownloadCSV()


        End If




    End Sub

    Protected Sub Button2_Click(sender As Object, e As EventArgs)

    End Sub








End Class

Aspx Code

Aspx 代码

<%@ Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site1.Master" CodeBehind="WebForm1.aspx.vb" Inherits="Leave12.WebForm1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

   <table>

       <tr>
          <%-- <td>
               <asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click" >Select From Date.....</asp:LinkButton>
           </td>
           <td>
               <asp:Calendar ID="Calendar1" runat="server" Visible="false" OnSelectionChanged="Calendar1_SelectionChanged" ></asp:Calendar>
           </td>
           <td>
               <asp:TextBox ID="TextBox1" ReadOnly="true" runat="server"></asp:TextBox>
           </td>--%>

           <td>
           <asp:Label ID="Label1" runat="server" Text="Please enter From Date"></asp:Label>
          </td>
           <td>
               <asp:TextBox ID="TextBox1" TextMode="Date" runat="server"></asp:TextBox>
           </td>
           <td>
               <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please enter From Date" Display="Dynamic" ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
           </td>

       </tr>
       <tr>
          <%-- <td>
               <asp:LinkButton ID="LinkButton2" runat="server" OnClick="LinkButton2_Click">Select To Date.....</asp:LinkButton>
           </td>
           <td>
               <asp:Calendar ID="Calendar2" runat="server" Visible="false" OnSelectionChanged="Calendar2_SelectionChanged" ></asp:Calendar>
           </td>
           <td>
               <asp:TextBox ID="TextBox2" ReadOnly="true" runat="server"></asp:TextBox>
           </td>--%>

           <%--<td>
               <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Please enter To Date" Display="Dynamic" ControlToValidate="TextBox2"></asp:RequiredFieldValidator>
           </td>--%>
           <td>
               <asp:Label ID="Label2" runat="server" Text="Please enter To Date"></asp:Label>
           </td>
           <td>
               <asp:TextBox ID="TextBox2" TextMode="Date" runat="server"></asp:TextBox>
           </td>
           <td>
               <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Please enter To Date" Display="Dynamic" ControlToValidate="TextBox2"></asp:RequiredFieldValidator>
           </td>
           <td>
               <asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="To Date should be greater than From Date" Display="Dynamic" Operator="GreaterThanEqual" ControlToCompare="TextBox1" ControlToValidate="TextBox2"></asp:CompareValidator>
           </td>

       </tr>
       <tr>

           <td>
               <asp:Label ID="Label3" runat="server" Text="Please select Leave Type"></asp:Label>
           </td>
           <td>
               <asp:RadioButtonList RepeatDirection="Horizontal" ID="RadioButtonList1"   runat="server" >
                   <asp:ListItem Selected="True" >Casual Leave</asp:ListItem>
                   <asp:ListItem>Sick Leave</asp:ListItem>
                   <asp:ListItem>Earned Leave</asp:ListItem>
               </asp:RadioButtonList>




           </td>



       </tr>
       <%--<tr>
           <td>
               <asp:Label ID="Label2" runat="server" Text="Reason"></asp:Label>
           </td>
           <td>
               <asp:TextBox ID="TextBox3" TextMode="MultiLine" Rows="5" Columns="50" runat="server"></asp:TextBox>
           </td>
           <td>
               <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="Please select Reason" ControlToValidate="TextBox3" Display="Dynamic"></asp:RequiredFieldValidator>
           </td>
       </tr>--%>
       <tr>
           <td>
               <asp:Label ID="Label4" runat="server" Text="Reason"></asp:Label>
           </td>
           <td>
               <asp:TextBox ID="TextBox3" TextMode="MultiLine" MaxLength="250" Rows="5" Columns="50" runat="server"></asp:TextBox>
           </td>
           <td>
               <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Please provide reason for leave" Display="Dynamic" ControlToValidate="TextBox3"></asp:RequiredFieldValidator>
           </td>
           <td>
               <asp:RegularExpressionValidator ID="RegularExpressionValidator1" ValidationExpression="^[\s\S]{0,100}$" runat="server" ErrorMessage="Please enter maximum of 250 characters" Display="Dynamic" ControlToValidate="TextBox3"></asp:RegularExpressionValidator>
           </td>
       </tr>
       <tr>
           <td>
               <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
           </td>
           <td>
               <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Reset" />
           </td>
       </tr>


   </table>
</asp:Content>