我有一个dropdownlist
,我希望用特定值和特定文本填充。我没有使用datasource
,但我手动建立连接并在代码中检索数据。如何填充此dropdownlist
?如果我用datareader
读取数据并递增数组,我只得到值或文本。这是我到目前为止所做的,但这是完全错误的:
//connection string etc goes here
Dbcmd2.CommandText = "select dept,deptname from table"
Dim dr As SqlClient.SqlDataReader
dr = Dbcmd2.ExecuteReader
Dim i As Integer
Dim arydept As New arraylist
While dr.Read
arydept.Add(dr1("dept"))
End While
ddldept.datasource = arydept
ddldept.DataTextField = ????????
ddldept.DataValueField = dr("dept")
ddldept.DataBind()
如何在不为Department
创建类对象的情况下使其工作?无论如何还是应该创建类对象吗?
答案 0 :(得分:4)
你有什么特别的理由可以正常的方式吗?
Dbcmd2.CommandText = "select dept,deptname from table"
Dim dr As SqlClient.SqlDataReader = Dbcmd2.ExecuteReader
While dr.Read()
ddldept.Items.Add(new ListItem(dr("deptname"),dr("dept"))
End While
' ddldept is now populated with all items from the query
答案 1 :(得分:2)
您已经在使用阅读器,只需将其弹出到DataTable并绑定:
//connection string etc goes here
Dbcmd2.CommandText = "select dept,deptname from table"
Dim dr As SqlClient.SqlDataReader
dr = Dbcmd2.ExecuteReader
Dim myData as DataTable
If dr.HasRows Then
myData.Load(dr)
End If
ddldept.datasource = myData
ddldept.DataTextField = myData("myTextField")
ddldept.DataValueField = myData("dept")
ddldept.DataBind()
答案 2 :(得分:1)
如果使用字典对象,则可以存储名称和值,而不是使用ArrayList。
这样的事情应该这样做
Dim All As New Dictionary(Of String, String)
All.Add("Test", 1)
All.Add("Test2", 2)
test.DataSource = All
test.DataTextField = "Key"
test.DataValueField = "Value"
test.DataBind()
答案 3 :(得分:1)
您可以简单地创建列表项并将其添加到下拉列表中,而不是使用datasource / databind()方法。
dr = Dbcmd2.ExecuteReader
Dim i As Integer
Dim arydept As New arraylist
ddldept.Items.Clear()
While dr.Read
ddldept.Items.Add(new ListItem(dr1("dept"), dr1("dept")))
End While
答案 4 :(得分:1)
这个怎么样?
ddldept.Items.Clear()
While dr.Read
ListItem item = New ListItem()
item.Text = dr("deptname").ToString()
item.Value = dr("dept").ToString()
ddldept.Items.Add(item)
End While