ASP.NET - Hashtable 객체
- 이전 페이지 WebForms ArrayList
- 다음 페이지 WebForms SortedList
Hashtable 객체는 키/값 쌍으로 표시된 항목을 포함합니다。
Hashtable 생성
Hashtable 객체는 키/값 쌍으로 표시된 항목을 포함합니다. 키는 인덱스로 사용되며, 키를 검색하여 값을 빠르게 검색할 수 있습니다。
Add() 메서드를 사용하여Hashtable에 항목을 추가합니다。
아래 코드는 mycountries라는Hashtable을 생성하고 네 가지 요소를 추가합니다:
<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>
데이터 바인딩
Hashtable 객체는 다음과 같은 컨트롤에 자동으로 텍스트와 값을 생성할 수 있습니다:
- asp:RadioButtonList
- asp:CheckBoxList
- asp:DropDownList
- asp:Listbox
RadioButtonList 컨트롤에 데이터를 바인딩하려면 먼저 .aspx 페이지에서 RadioButtonList 컨트롤을 생성해야 합니다 (asp:ListItem 요소가 없음)
<html> <body> <form runat="server"> <asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" /> </form> </body> </html>
그런 다음 목록을 구성하는 스크립트를 추가합니다:
<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>
사용자가 RadioButtonList 컨트롤의 항목을 클릭할 때 실행되는 서브루틴을 추가합니다. 어떤 단일 선택 버튼을 클릭하면 label에 텍스트가 나타납니다:
<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