I'm working on populating a listbox with a datatable that is being filled from a database. Here is the relevant code.
Private Sub frmMainMenu_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Load data we need from the database
Dim commandCraneType As New OleDbCommand("SELECT Name FROM CraneType WHERE Girders = 'Single Girder'", gConnection)
Dim adapterCraneType As New OleDbDataAdapter(commandCraneType)
Dim dTableCraneType As New DataTable()
'Fill datatables and controls
adapterCraneType.Fill(dTableCraneType)
lboCraneType.DataSource = dTableCraneType
lboCraneType.DisplayMember = "Name"
End Sub
Private Sub lboCraneType_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lboCraneType.SelectedIndexChanged
'Set the gCraneType global variable!
gCraneType = lboCraneType.SelectedItem
Debug.Print(gCraneType)
End Sub
The listbox properly populates with the text values in the Name field from the database. However when I select that item in the listbox, the debug tells me that gCraneType has been assigned System...DataRowView, and I get an exception saying I cannot cast that type to a String. I do not understand why the Names are showing up properly in the listbox but the selections are a data type.
Thanks for any help you offer :)
Change:
Private Sub lboCraneType_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lboCraneType.SelectedIndexChanged
'Set the gCraneType global variable!
gCraneType = lboCraneType.SelectedItem
Debug.Print(gCraneType)
End Sub
To:
Private Sub lboCraneType_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lboCraneType.SelectedIndexChanged
'Set the gCraneType global variable!
Dim drv As DataRowView = lboCraneType.SelectedItem
gCraneType = drv("Name").ToString
End Sub
Thank you for your help in the commnets.