ASP.NET - Objeto Hashtable
- Página anterior ArrayList WebForms
- Página siguiente SortedList WebForms
El objeto Hashtable contiene elementos representados por pares de clave/valor.
Crear Hashtable
El objeto Hashtable contiene elementos representados por pares de clave/valor. La clave se utiliza como índice y, mediante la búsqueda de su clave, se puede realizar una búsqueda rápida de valores.
Agregue elementos al Hashtable mediante el método Add().
El siguiente código crea un Hashtable llamado mycountries y agrega cuatro elementos:
<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") fin if fin sub </script>
Vinculación de datos
El objeto Hashtable puede generar automáticamente texto y valores para los siguientes controles:
- asp:RadioButtonList
- asp:CheckBoxList
- asp:DropDownList
- asp:Listbox
Para vincular datos a un control RadioButtonList, primero cree un control RadioButtonList en una página .aspx (sin elementos asp:ListItem)
<html> <body> <form runat="server"> <asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" /> </form> </body> </html>
Luego agregamos el script para construir la lista:
<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() fin if fin sub </script> <html> <body> <form runat="server"> <asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" /> </form> </body> </html>
Luego agregamos un subprocedimiento que se ejecutará cuando el usuario haga clic en algún elemento del control RadioButtonList. Cuando se hace clic en un botón de opción, aparecerá un texto en el 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() fin if fin sub sub displayMessage(s como Object, e como EventArgs) lbl1.text="Su país favorito es: " & rb.SelectedItem.Text fin 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>
Notas:No puede seleccionar el método de ordenación de los elementos que desea agregar a la Hashtable. Si desea ordenar los elementos alfabéticamente o numéricamente, utilice el objeto SortedList.
- Página anterior ArrayList WebForms
- Página siguiente SortedList WebForms