ListBoxes

D

David Gouge

Hi All,

Hope someone can point me in the right direction.

Doing a very simple app in C# .net 2.0 where i have a listbox bound to a
datatable (StaffTable) with the DisplayMember being the name field and
the ValueMember being the number field. I have the following code in
the form's constructor:

StaffList.DataSource = StaffTable;
StaffList.DisplayMember = "name";
StaffList.ValueMember = "number";

What i need to do is grab the data from the ValueMember field for the
selected ListBox item. So far i have only found the following way to do
this:

DataRowView aDrv = (DataRowView)StaffList.SelectedItem;
string number = aDrv.Row[2].ToString().Trim();

....which seems a bit of a long way round.

In .net 1.1, all i had to do was:

string number = StaffList.Items[StaffList.SelectedIndex].Value

....but this does not build in 2.0.

So, is the way i'm doing it the only way in 2.0 or is there are more
elegant way as in my 1.1 code?

Thanks in advance.
 
N

Nicholas Paldino [.NET/C# MVP]

David,

What's wrong with using the SelectedValue property? It will return the
value that the list is bound to (and I'm surprized that the listbox worked
in .NET 1.1 with the Items collection when it was data bound).

You just have to do this:

// Get the number.
string number = StaffList.SelectedValue.ToString();

If you want an int, you can do this:

// Get the number.
int number = (int) StaffList.SelectedValue;

Hope this helps.
 
D

David Gouge

Nicholas said:
David,

What's wrong with using the SelectedValue property? It will return the
value that the list is bound to (and I'm surprized that the listbox worked
in .NET 1.1 with the Items collection when it was data bound).

You just have to do this:

// Get the number.
string number = StaffList.SelectedValue.ToString();

If you want an int, you can do this:

// Get the number.
int number = (int) StaffList.SelectedValue;

Hope this helps.

<slaps forehead> Cheers, knew it must be nice and simple.

Thanks for the reply Nicholas.

Dave
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top