Reputation: 69
Sometimes simple code will make us big confusion. I researched this questions in internet from past few hours.
I have a listbox, data will load from Access table. When i selected an item in listbox, i wanted to show that item in a textbox.
i have tried some code as below, nothing worked for me:
Private Sub listBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles listBox1.SelectedIndexChanged
For i As Integer = 0 To listBox1.SelectedItems.Count - 1
textBox1.Text &= DirectCast(listBox1.SelectedItems(i), DataRowView)(1).ToString & vbCrLf
Next
End Sub
Private Sub listBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles listBox1.SelectedIndexChanged
textBox1.Text = listBox1.SelectedItem.Value
End Sub
Here is the code that will give values to listbox from access table
Dim dataAdapter As New OleDbDataAdapter("select * from eval", connection)
Dim ds As DataSet = New DataSet
dataAdapter.Fill(ds, "eval")
listBox1.DataSource = ds
listBox1.DisplayMember = "eval"
listBox1.ValueMember = "eval.eval"
Upvotes: 1
Views: 63987
Reputation: 5545
The listBox1.SelectedItem will give you back a System.Data.Datarow, because that is what you put in there. If you want to display the same text in the textbox that is displayed for the listbox, you can simply use this:
Private Sub listBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles listBox1.SelectedIndexChanged
textBox1.Text = listBox1.text
End Sub
If you want a value from another field (you do not show your fields so lets pretend there is one called "FirstName") you could do this:
Private Sub listBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles listBox1.SelectedIndexChanged
Dim DR as datarow = listBox1.SelectedItem
textBox1.Text = DR("FirstName")
End Sub
Upvotes: 2
Reputation: 870
Here is a simple example of what you can do. Lets say you have a list box with 4 items: VB.Net,C#,Java and Python. First, make the listbox SelectionMode = MultiSimple
. If I understood you correctly, you want all the items that have been selected in the listbox to be transfered to a text box. You can do that by wrtining this code:
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
TextBox1.Clear()
For Each Item As Object In ListBox1.SelectedItems
TextBox1.AppendText(Item.ToString + Environment.NewLine)
Next
End Sub
Here are the results :
(Sorry for the bad quality)
Upvotes: 2