Binding a listbox with value and text
i am creating a listCollection like this:
Dim risList As New ListItemCollection
Dim cUser As New clsUser()
Dim ds As DataSet = cUser.GetUserRIS(1)
For Each row In ds.Tables(0).Rows
Dim li As New ListItem
li.Text = cLookup.GetxName(row.Item("xCode"))
li.Value = row.Item("xCode")
risList.Add(li)
Next
i then need to bind the dropdownlist with it
ddlRIS.DataSource = risList
ddlRIS.DataBind()
however my text and value in the drop down, both show the text. When i debug the above code li.Value = row.Item("risCode") shows the Code correctly, but why does it not reflect when i try to bind it to 开发者_如何学Cthe dropdown list?
Why don't you add it directly to the ListBox/DropDownList as a workaround, your way should work though.
Dim risList As New ListItemCollection
Dim cUser As New clsUser()
Dim ds As DataSet = cUser.GetUserRIS(1)
For Each row In ds.Tables(0).Rows
Dim li As New ListItem
li.Text = cLookup.GetxName(row.Item("xCode"))
li.Value = row.Item("xCode")
ddlRIS.Items.Add(li)
Next
And now you can access the Text and Value by: (respectively)
Dim txt1 As String, val1 As String
txt1 = ddlRIS.SelectedItem.Text
val1 = ddlRIS.SelectedItem.Value
Hope that helps.
Did you Set the DataValueField on the drop down to the Text property? What property is the value bound to?
Also, you could alternatively add the items to the drop down, rather than construct a ListItemCollection and bind it to the list.
Lastly, as a side note, the ListItem class, when the value property doesn't store anything, it by default returns the text value instead. So I don't know if its a binding issue, or if this is whats happening...
精彩评论