easy way for list.selected to string?

archer_coal

Well-known member
Joined
Apr 4, 2003
Messages
96
i have a dataset populating my listbox like so:

Code:
Public Function bind_listbox(ByVal str_column As String)
         Make the data adapter.
        m_DataAdapter = New OleDbDataAdapter( _
          "SELECT * FROM " & str_column & " order by id", _
          "Provider=Microsoft.Jet.OLEDB.4.0;" & _
          "Data Source=C:\data\20304aa1.mdb")

         Fill the DataSet.
        m_DataAdapter.Fill(m_DataSet)

        ListBox1.DataSource = m_DataSet.Tables(0)
        ListBox1.DisplayMember = "1"


        
    End Function

in a Doubleclick event of the listbox, i would like to populate a text box with the corrosponding data of the list box.
Sounds like it should be simple but i keep getting errors telling me i cant convert to string.

Code:
Private Sub Listbox1_doubleclick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.DoubleClick
        Dim str As String
        str = ListBox1.SelectedItem
        TextBox1.Text = str

    End Sub

ive also tried a .gettype.tostring with no success but maybe i wasnt doing it correctly.
any ideas?
 
Try ListBox1.Text instead of ListBox1.SelectedItem or (maybe this will work?) use ListBox1.SelectedItem.ToString().

SelectedItem returns an object of whatever type you have in there. Since youre binding, its an object that represents the data in the database. To convert the object to a string, you can use ToString (as I showed above) or even easier, use the string thats displayed in the ListBox, which is the Text property (also shown above).

-ner
 
re:

using Listbox1.Text works but Listbox1.SelectedItem.ToString() produces System.Data.DataRowView instead of the literal string.
This may be helpful later when i try to update the database =)
So listbox1.Text it is.



Thanks for the help.
 
Yeah, the Text property is an easy way.
But do also consider the property ValueMember!
In your code snippet you used the DisplayMember property. When your code is correct then your table has to have a column named "1".
So DisplayMember tells thet the column named "1" of your table has to be displayed in the listbox.
And "tada" - here comes ValueMember: That tells which one of the columns will return its value when the listbox is - lets say for example - doubleclicked, :D or when you use Listbox1.SelectedValue.
I think thats easy as well, but much more flexible!
 
Back
Top