ASP.NET使用RadioButton控件
RadioButton控件是一种单选按钮控件,用户可以在页面中添加一组RadioButton控件,通过为所有的单选按钮分配相同的组名(GroupName),来强制执行从给出的所有选项集合中仅选择一个选项。
RadioButton控件如下图所示:
注:RadioButton控件总是成组出现的。并且一次只能选择一个。
RadioButton控件的属性
将工具箱中的RadioButton控件拖动到aspx页面中,或者在页面中选择一个RadioButton控件时,RadioButton控件的属性就显示在了“属性”窗口中。如下图所示:
在“属性”窗口中点击任意一个属性时,都会在窗口底部显示出对该属性的解释。
下面介绍RadioButton控件的一些重要属性:
- AccessKey属性
指定一个导向RadioButton控件的键盘快捷键。
- AutoPostBack属性
用于在单选按钮被选中或取消选中时,自动向服务器端回传包含该RadioButton控件的表单。
- GroupName属性
使用GroupName属性指定一组单选按钮,以创建一组互相排斥的控件。如果用户在页面中添加了一组RadioButton控件,可以将所有单选按钮的GroupName属性值设为同一个值,来强制执行在给出的所有选项集中仅有一个处于被选中状态。
- Checked属性
如果RadioButton控件被选中,则RadioButton控件的Checked属性值为True,否则为False。
- TextAlign属性
RadioButton控件可以通过Text属性指定要在控件中显示的文本。当RadioButton控件的TextAlign属性值为Left时,文本显示在单选按钮的左侧;当RadioButton控件的TextAlign属性值为Right时,文本显示在单选按钮的右侧。
RadioButton控件的常用事件
RadioButton控件常用的事件是CheckedChanged。当RadioButton控件的选中状态发生改变时引发该事件。
实例
下面的aspx页面包含了3个RadioButton控件。程序代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ShowRadioButton.aspx.cs" Inherits="ShowRadioButton" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
if (RadioButton1.Checked)
Label1.Text = RadioButton1.Text;
if (RadioButton2.Checked)
Label1.Text = RadioButton2.Text;
if (RadioButton3.Checked)
Label1.Text = RadioButton3.Text;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ASP.NET使用RadioButton控件-www.baike369.com</title>
</head>
<body>
<form id="form1" runat="server">
<div>
您最喜欢哪一项球类活动?
<ul>
<li>
<asp:RadioButton
ID="RadioButton1"
Text="篮球"
GroupName="Sports"
runat="server" />
</li>
<li>
<asp:RadioButton
ID="RadioButton2"
Text="足球"
GroupName="Sports"
runat="server" />
</li>
<li>
<asp:RadioButton
ID="RadioButton3"
Text="羽毛球"
GroupName="Sports"
runat="server" />
</li>
</ul>
<asp:Button
ID="Button1"
runat="server"
Text="提交" OnClick="Button1_Click" />
<hr />
<asp:Label
ID="Label1"
runat="server">
</asp:Label>
</div>
</form>
</body>
</html>
执行结果如下:
在上面的代码中,RadioButton控件通过GroupName属性组成了单选按钮组。3个RadioButton控件中一次只能选中一个。
在这里,选择“羽毛球”项,然后点击“提交”按钮,即可显示出“羽毛球”信息。
提示
为了使用户将已经选择的答案显示在界面上,可以在RadioButton控件的CheckedChanged事件中,使用Checked属性来判断该RadionButton控件是否已被选中。如果已被选中,则将其显示出来。单选按钮RadioButton的CheckedChanged事件代码如下:
protected void Button1_Click(object sender, EventArgs e)
{
if (RadioButton1.Checked)
Label1.Text = RadioButton1.Text;
if (RadioButton2.Checked)
Label1.Text = RadioButton2.Text;
if (RadioButton3.Checked)
Label1.Text = RadioButton3.Text;
}