RadioButton控件分组

如果要对RadioButton控件进行分组,就要使用到其GroupName属性,GroupName值相同的控件被认为是一组的,在同一组RadioButton控件中你始终只能选择一项,但RadioButton控件的分组属性GroupName似乎也仅仅是起分组的作用而已,对获取选中项的值一点帮助都没有(个人观点),而使用RadioButtonList似乎是更好的方案,同一个RadioButtonList的选项自然被认为是一组,并且获取选中项的值也比RadioButton好多了。

Test.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>RadioButton分组</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:RadioButton ID="RadioButton1" Checked="true" runat="server" GroupName="Color" Text="Red" />
        <asp:RadioButton ID="RadioButton2" runat="server" GroupName="Color" Text="White" />
        <asp:RadioButtonList ID="Sex" runat="server" RepeatColumns="3">
            <asp:ListItem Value="1" Selected="true">Boy</asp:ListItem>
            <asp:ListItem Value="2">Girl</asp:ListItem>
        </asp:RadioButtonList><br />
        <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" /><br /><br />
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
     </div>
    </form>
</body>
</html>

Test.aspx.cs:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //
    }

    /// <summary>
    /// 显示选中值
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button1_Click(object sender, EventArgs e)
    {
        Label1.Text = "";

        //遍历Color  GroupName属性仅起分组作用,对取值毫无帮助? 有等研究!
        if (RadioButton1.Checked) Label1.Text += "Color" + ":" + RadioButton1.Text;
        if (RadioButton2.Checked) Label1.Text += "Color" + ":" + RadioButton2.Text;

        Label1.Text += "<br/>";

        //获取Sex值
        Label1.Text += "Sex" + ":" + Sex.SelectedItem.Value.ToString() + "(" + Sex.SelectedItem.Text + ")";
    }
}

注意RadioButtonList控件的RepeatColumns属性,将设置同一行上显示的选项数目,这对要将多个选项横向排列时特别有用!

评论: 0 | 引用: 0 | 查看次数: 10993
发表评论
登录后再发表评论!