VB.NET - How do you assign listbox current selection to textboxes?

Asked By kibika on 05-Jan-13 07:55 AM
Hello,

I'm having trouble retrieving data from a listbox in VB 2005.

My listbox is populated by a table from an Access database.

I'm trying to assign the current listbox selection to a textbox using:

If I want to get the text from the selected item in a ListBox, I could
use:
   Me.txtSelection.Text = Me.lstEmployees.Text


I'm assuming that this means that I'm trying to return the entire record
rather than a single field in the record.

Now,if you want to access other fields I'm trying to use:

Dim drv As DataRowView = DirectCast( lstEmployees.SelectedItem, DataRowView)
Me.txtSelection.Text = drv("firstName").ToString()

When running this code I get the following error:


"Unable to cast object of type 'System.String' to type 'System.Data.DataRowView'".

What am I doing wrong here.

And again Unfortunately I don't know how to return just a single field and I couldn't find anything in 'Help'.

Any assistance is greatly appreciated.

Thanks,
Tom Wilson replied to kibika on 05-Jan-13 12:04 PM
Hopefully the following code will help:

Public Class Form1
  Private dt As New DataTable
  Private loadform As Boolean   'Prevent execution of selectedindexchanged event when loading form
 
  Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  loadform = True
  buildtable()  'build a dummy datatable
 
  ListBox1.DataSource = dt
  ListBox1.DisplayMember = "LastName"
  loadform = False
  End Sub
 
  Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
  If Not loadform Then
    Dim dr As DataRowView = DirectCast(ListBox1.SelectedItem, DataRowView)
    TextBox1.Text = dr(0)
    TextBox2.Text = dr(1)
    TextBox3.Text = dr(2)
  End If
  End Sub
 
  Private Sub buildtable()
  Dim col1 As New DataColumn("FirstName", GetType(System.String))
  Dim col2 As New DataColumn("LastName", GetType(System.String))
  Dim col3 As New DataColumn("Phone", GetType(System.String))
 
  dt.Columns.Add(col1)
  dt.Columns.Add(col2)
  dt.Columns.Add(col3)
  For ix As Integer = 0 To 4
    Dim nr As DataRow = dt.NewRow
    nr(0) = "John" & ix.ToString
    nr(1) = "Smith" & ix.ToString
    nr(2) = "555-555-000" & ix.ToString
    dt.Rows.Add(nr)
  Next
  End Sub
End Class

How do you assign listbox current selection to textboxes? - kibika replied to Tom Wilson on 05-Jan-13 12:15 PM

Thanks a lot, it was what I was looking for.


Be blessed.
kibika