课程表

WebPages 教程

WebPages 参考手册

ASP.net Razor

ASP.net MVC

WebForms 教程

WebForms 参考手册

工具箱
速查手册

WebForms Hashtable

当前位置:免费教程 » 程序设计 » ASP.net

Hashtable 对象包含用键/值对表示的项目。

创建 Hashtable

Hashtable 对象包含用键/值对表示的项目。键被用作索引,通过搜索其键,可以实现对值的快速搜索。

通过 Add() 方法向 Hashtable 添加项目。

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

  1. <script runat="server">
  2. Sub Page_Load
  3. if Not Page.IsPostBack then
  4. dim mycountries=New Hashtable
  5. mycountries.Add("C","China")
  6. mycountries.Add("S","Sweden")
  7. mycountries.Add("F","France")
  8. mycountries.Add("I","Italy")
  9. end if
  10. end sub
  11. </script>

数据绑定

Hashtable 对象可为下面这些控件自动地生成文本和值:

  • asp:RadioButtonList
  • asp:CheckBoxList
  • asp:DropDownList
  • asp:Listbox

如需把数据绑定到某个 RadioButtonList 控件,首先请在一个 .aspx 页面中创建 RadioButtonList 控件(没有任何 asp:ListItem 元素)

  1. <html>
  2. <body>
  3.  
  4. <form runat="server">
  5. <asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" />
  6. </form>
  7.  
  8. </body>
  9. </html>

然后添加构建列表的脚本:

  1. <script runat="server">
  2. sub Page_Load
  3. if Not Page.IsPostBack then
  4. dim mycountries=New Hashtable
  5. mycountries.Add("C","China")
  6. mycountries.Add("S","Sweden")
  7. mycountries.Add("F","France")
  8. mycountries.Add("I","Italy")
  9. rb.DataSource=mycountries
  10. rb.DataValueField="Key"
  11. rb.DataTextField="Value"
  12. rb.DataBind()
  13. end if
  14. end sub
  15. </script>
  16.  
  17. <html>
  18. <body>
  19.  
  20. <form runat="server">
  21. <asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" />
  22. </form>
  23.  
  24. </body>
  25. </html>

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

  1. <script runat="server">
  2. sub Page_Load
  3. if Not Page.IsPostBack then
  4. dim mycountries=New Hashtable
  5. mycountries.Add("C","China")
  6. mycountries.Add("S","Sweden")
  7. mycountries.Add("F","France")
  8. mycountries.Add("I","Italy")
  9. rb.DataSource=mycountries
  10. rb.DataValueField="Key"
  11. rb.DataTextField="Value"
  12. rb.DataBind()
  13. end if
  14. end sub
  15.  
  16. sub displayMessage(s as Object,e As EventArgs)
  17. lbl1.text="Your favorite country is: " & rb.SelectedItem.Text
  18. end sub
  19. </script>
  20.  
  21. <html>
  22. <body>
  23.  
  24. <form runat="server">
  25. <asp:RadioButtonList id="rb" runat="server"
  26. AutoPostBack="True" onSelectedIndexChanged="displayMessage" />
  27. <p><asp:label id="lbl1" runat="server" /></p>
  28. </form>
  29.  
  30. </body>
  31. </html>

显示这个例子

注释:您无法选择添加到 Hashtable 的项目的排序方式。如需对项目进行字母排序或数字排序,请使用 SortedList 对象。

转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号