我已经使用代码将哈希表与listbox绑定,但我不能。
任何人都请帮我理解哈希表和绑定概念......
的.aspx
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Hashtable.aspx.vb" Inherits="Hashtable" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<br />
<asp:ListBox ID="ListBox1" runat="server"></asp:ListBox><br />
</div>
</form>
</body>
</html>
.aspx.vb:
#Region "Namespaces"
Imports System.Data
Imports System.IO
Imports System.Net.Mail
#End Region
Partial Class Hashtable
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim ht As New Hashtable
ht.Items.Add("1", "Sunday")
ht.Items.Add("2", "Monday")
ht.Items.Add("3", "Tuesday")
ht.Items.Add("4", "Wednesday")
ht.Items.Add("5", "Thursday")
ht.Items.Add("6", "Friday")
ht.Items.Add("7", "Saturday")
ListBox1.DataSource = ht
ListBox1.DataValueField = "Key"
ListBox1.DataTextField = "Value"
ListBox1.DataBind()
End Sub
End Class
答案 0 :(得分:2)
我认为可以将数据绑定到哈希表。
这样的事情应该有效
Hashtable myHashTable = new HashTable();
myHashTable.Add ("First", "The first item");
myHashTable.Add ("Second", "The second item");
myHashTable.Add ("Third", "The third item");
ddlMyDropDownList.DataSource = myHashTable.Keys;
ddlMyDropDownList.DataBind();
在您的代码中:
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim ht As Hashtable = New Hashtable(7)
ht.Add("1", "Sunday")
ht.Add("2", "Monday")
ht.Add("3", "Tuesday")
ht.Add("4", "Wednesday")
ht.Add("5", "Thursday")
ht.Add("6", "Friday")
ht.Add("7", "Saturday")
ListBox1.DataSource = ht
ListBox1.DataValueField = "Key"
ListBox1.DataTextField = "Value"
ListBox1.DataBind()
End Sub
结束班
答案 1 :(得分:0)
不要使用旧的Hashtable类,而是使用替换字典。 (几乎)来自System.Collections命名空间的所有类都是如此。
虽然你可以尝试
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim ht As New Hashtable
ht.Items.Add("1", "Sunday")
ht.Items.Add("2", "Monday")
ht.Items.Add("3", "Tuesday")
ht.Items.Add("4", "Wednesday")
ht.Items.Add("5", "Thursday")
ht.Items.Add("6", "Friday")
ht.Items.Add("7", "Saturday")
foreach (var item in ht)
{
ListBox1.Items.Add(item.Value)
}
End Sub