ASP.NET Web Forms - SortedList 对象

文章介绍了如何在ASP.NET中使用SortedList对象存储有序数据,并通过Add()方法添加项目。接着展示了如何将SortedList对象的数据绑定到RadioButtonList控件,设置DataValueField和DataTextField属性以显示键和值。当用户选择RadioButtonList中的项时,会触发事件并显示所选国家的名称。
摘要由CSDN通过智能技术生成

SortedList 对象

SortedList对图像包含用键/值得显示的项目。SortedList对图像按顺序或数字顺序自动地对项目进行排序。

通过 Add() 方法向 SortedList 添加项目。通过 TrimToSize() 方法把 SortedList 调整为最小尺寸。

下面的代码创建了一个名为 mycountries 的 SortedList 对象,并添加了四个元素:

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New SortedList
mycountries.Add("N","Norway")
mycountries.Add("S","Sweden")
mycountries.Add("F","France")
mycountries.Add("I","Italy")
end if
end sub
</script>


数据绑定

SortedList 对象可为下一个列表的控件自动生成文本和值:

  • asp:单选按钮列表
  • asp:复选框列表
  • asp:下拉列表
  • asp:列表框

为了绑定数据到RadioButtonList控件,首先要在.aspx页面中创建一个RadioButtonList控件(不带任何asp:ListItem元素):

<html>
<body>

<form runat="server">
<asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" />
</form>

</body>
</html>

然后添加创建列表的脚本,并绑定列表中的值到 RadioButtonList 控件:

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New SortedList
mycountries.Add("N","Norway")
mycountries.Add("S","Sweden")
mycountries.Add("F","France")
mycountries.Add("I","Italy")
rb.DataSource=mycountries
rb.DataValueField="Key"
rb.DataTextField="Value"
rb.DataBind()
end if
end sub
</script>

<html>
<body>

<form runat="server">
<asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" />
</form>

</body>
</html>

然后我们添加一个子示例程序,当用户点击RadioButtonList控件中的某个项目时,该子示例程序会被执行。当某个单选按钮被点击文本出时:label

实例

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New SortedList
mycountries.Add("N","Norway")
mycountries.Add("S","Sweden")
mycountries.Add("F","France")
mycountries.Add("I","Italy")
rb.DataSource=mycountries
rb.DataValueField="Key"
rb.DataTextField="Value"
rb.DataBind()
end if
end sub

sub displayMessage(s as Object,e As EventArgs)
lbl1.text="Your favorite country is: " & rb.SelectedItem.Text
end sub
</script>

<html>
<body>

<form runat="server">
<asp:RadioButtonList id="rb" runat="server"
AutoPostBack="True" onSelectedIndexChanged="displayMessage" />
<p><asp:label id="lbl1" runat="server" /></p>
</form>

</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

智慧浩海

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值