在这里只写,绑定数据库数据的RadioButtonList控件:

一:

首先,先在数据库中建立一张表:

1 CREATE TABLE KK
2 (
3 id INT,
4 [name] VARCHAR(20),
5 )

然后插入数据:

RadioButtonList控件-LMLPHP
1 INSERT INTO KK (id, [name]) VALUES (1, '张三')
2 INSERT INTO KK (id, [name]) VALUES (2, '李四')
3 INSERT INTO KK (id, [name]) VALUES (3, '王五')
4 INSERT INTO KK (id, [name]) VALUES (4, '赵六')
5 ·
6 ·
7 ·
8 ·
9 ·
RadioButtonList控件-LMLPHP

这是最终建立的表:

RadioButtonList控件-LMLPHP

二:

前台代码:

 <div>
<asp:RadioButtonList ID="RadioButtonList1" runat="server" RepeatDirection="Horizontal"></asp:RadioButtonList>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick ="Button1_Click"/><br /><br />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>

*其中:RepeatDirection="Horizontal"是设置其选项横向显示。

后台代码(Page_Load):

 protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
/* 为什么判断IsPostBack:当你需要执行一些仅需要在页面第一次浏览时执行的事件
* 比如页面初始化,数据绑定之类的操作时,需要将操作放在if(!IspostBack)里面,
* 这样当你在点击页面中的按钮或者执行其他回发事件时,不贵再次初搜索始化或者
* 重复绑定数据,提高了执行效率。
*/
{
string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString; SqlConnection connection = new SqlConnection(connectionString); connection.Open(); string sql = "SELECT * FROM KK"; SqlCommand cmd = new SqlCommand(sql, connection); SqlDataReader sdr = cmd.ExecuteReader(); //任意给的字段名,只要是想显示在界面上的就行。其值给了:Text
this.RadioButtonList1.DataTextField = "name"; //任意给得字段名,只要是想在后台看到前台看不到的数据就行。其值给了:Value
this.RadioButtonList1.DataValueField = "id";//此字段可以去掉。value的值默认为Text的值。 this.RadioButtonList1.DataSource = sdr; this.RadioButtonList1.DataBind(); sdr.Close(); connection.Close();
}
}

后台代码(Button1):

 /// <summary>
/// Button1按钮的单机事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button1_Click(object sender, EventArgs e)
{
string s = string.Empty; for (int i = ; i < RadioButtonList1.Items.Count; i++)
{
if (RadioButtonList1.Items[i].Selected)
{
s = RadioButtonList1.Items[i].Text;
}
} this.Label1.Text = "你选中的是:" + s;
}

最终效果:

RadioButtonList控件-LMLPHP

以上就是RadioButtonList控件。

05-06 05:04