我是贝琳达。我尝试使用以下鳕鱼将hashtable
与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
执行时我收到以下错误:
Data source is an invalid type. It must be either an IListSource, IEnumerable, or IDataSource.
为什么会这样......以及我应该做什么...我不想使用字典而只想使用hashtable
。
我正在使用vb.net作为一种语言而不是c# 有人请帮助我,请清除我的怀疑。
提前致谢
答案 0 :(得分:0)
为什么不使用Dictionary而不是哈希表呢?这是一个更好的解决方案,因为您添加的值具有唯一键(哈希表中不是这种情况),您的值将被强类型化:
#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 dictionary As New Dictionary(Of Integer, String)
dictionary.Add(1, "Sunday")
dictionary.Add(2, "Monday")
dictionary.Add(3, "Tuesday")
dictionary.Add(4, "Wednesday")
dictionary.Add(5, "Thursday")
dictionary.Add(6, "Friday")
dictionary.Add(7, "Saturday")
ListBox1.DataSource = dictionary
ListBox1.DataBind()
End Sub
End Class
DataSource
属性并不支持所有类型的集合。虽然不支持Hashtable,但词典是。