[英]How can I bind listbox with hashtable in ASP.net
我是贝琳达。 我试过下面的鳕鱼绑定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#。有人请帮助我,请清除我的疑问。
提前致谢
为什么不使用字典而不是哈希表? 这是一个更好的解决方案,因为您添加的值具有唯一键(散列表中不是),并且您的值将被强类型化:
#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,但支持Dictionary。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.