ASP.NET Web Forms - Objeto Hashtable


El objeto Hashtable contiene elementos representados por pares clave/valor.


Examples

Pruébalo - Ejemplo

Hashtable RadiobuttonList 1

Hashtable RadiobuttonList 2

Hashtable DropDownList


Crear Hashtable

El objeto Hashtable contiene elementos representados por pares clave/valor. La clave se utiliza como índice; buscando la clave, se puede lograr una búsqueda rápida del valor.

Los elementos se agregan al Hashtable mediante el método Add().

El siguiente código crea un objeto Hashtable llamado mycountries y agrega cuatro elementos:

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


Enlace 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 enlazar datos al control RadioButtonList, primero debe crear un control RadioButtonList en la página .aspx (sin ningún elemento asp:ListItem):

<html>
<body>

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

</body>
</html>

Luego agregue el script que crea la lista y enlace los valores de la lista al control RadioButtonList:

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New Hashtable
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>

Luego agregamos una subrutina que se ejecuta cuando el usuario hace clic en un elemento del control RadioButtonList. Cuando se hace clic en un botón de opción, aparece una línea de texto en el label:

Ejemplo

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New Hashtable
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>

Ver demostración »

Nota:No puede elegir el orden de los elementos agregados al Hashtable. Si necesita ordenar los elementos alfabética o numéricamente, use el objeto SortedList.


Otras extensiones