Assigning ListBox Current Selection to TextBox

  • Thread starter Thread starter sajones
  • Start date Start date
S

sajones

Hello,

I'm a novice user having troubles retrieving data from a listbox in VB
Express 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:
"Me.txtSelection.Text = CStr(lstUsers.Items(Me.lstUsers.SelectedIndex))"

When running this code I get the following error:

"InvalidCastException was unhandled. Conversion from type'DataRowView' to
type 'String' is not valid."

I'm assuming that this means that I'm trying to return the entire record
rather than a single field in the record. 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,
Scott
 
Hi,

Hello,

I'm a novice user having troubles retrieving data from a listbox in VB
Express 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:
"Me.txtSelection.Text = CStr(lstUsers.Items(Me.lstUsers.SelectedIndex))"

When running this code I get the following error:

"InvalidCastException was unhandled. Conversion from type'DataRowView' to
type 'String' is not valid."

If you want to get the text from the selected item in a ListBox, you could
use:
Me.txtSelection.Text = Me.lstUsers.Text
I'm assuming that this means that I'm trying to return the entire record
rather than a single field in the record.

True, if you want to access other fields you can use:

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

Note that if you bind the TextBox to the same BindingSource as the ListBox
it can automatically show the selected listbox text.

HTH,
Greetings
 
Hi,



If you want to get the text from the selected item in a ListBox, you could

use:
Me.txtSelection.Text = Me.lstUsers.Text


True, if you want to access other fields you can use:

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

Note that if you bind the TextBox to the same BindingSource as the ListBox

it can automatically show the selected listbox text.

HTH,
Greetings

You're a genius! It worked great! Thanks for the help.

So much for online help...

Thanks,
Scott
 
Back
Top