简体   繁体   中英

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 the dropdown list?

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...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM