ASP.NET - Object ng Hashtable
- หน้าก่อนหน้า WebForms ArrayList
- หน้าต่อไป WebForms SortedList
Ang object ng Hashtable ay naglalaman ng mga item na inilalarawan ng pares ng key/value.
Magtatayo ng Hashtable
Ang object ng Hashtable ay naglalaman ng mga item na inilalarawan ng pares ng key/value. Ang key ay ginagamit bilang index, at pamamagitan ng paghahanap sa key, maaaring masagana ang paghahanap sa halaga.
Magdagdag ng item sa Hashtable sa pamamagitan ng Add() method.
Ang sumusunod na code ay nagtatayo ng isang Hashtable na may pangalan na mycountries at nagdagdag ng apat na elemento:
<script runat="server"> Sub Page_Load if Not Page.IsPostBack then dim mycountries=New Hashtable mycountries.Add("C","China") mycountries.Add("S","Sweden") mycountries.Add("F","France") mycountries.Add("I","Italy") end if end sub </script>
Data Binding
Ang object ng Hashtable ay maaaring gumawa ng teksto at halaga para sa mga sumusunod na control:
- asp:RadioButtonList
- asp:CheckBoxList
- asp:DropDownList
- asp:Listbox
Upang i-bind ang data sa isang RadioButtonList control, unang makapaglilikha ng RadioButtonList control sa isang .aspx page (walang asp:ListItem element)
<html> <body> <form runat="server"> <asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" /> </form> </body> </html>
Pagkatapos, magdagdag ng script na magpapatayo ng listahan:
<script runat="server"> sub Page_Load if Not Page.IsPostBack then dim mycountries=New Hashtable mycountries.Add("C","China") 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>
Pagkatapos, magdagdag tayo ng isang sub-procedure, na pupunta ito kapag ang isang item ng RadioButtonList control ay pinindot ng user.
<script runat="server"> sub Page_Load if Not Page.IsPostBack then dim mycountries=New Hashtable mycountries.Add("C","China") 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>
หมายเหตุ:คุณไม่สามารถเลือกวิธีการจัดลำดับของโครงการที่จะเพิ่มเข้ามาใน Hashtable ได้。หากต้องการจัดลำดับตามอักษรหรือตามตัวเลขของโครงการ โปรดใช้ตัวแปล SortedList。
- หน้าก่อนหน้า WebForms ArrayList
- หน้าต่อไป WebForms SortedList