binding a listbox

  • Thread starter Thread starter Michael Powe
  • Start date Start date
M

Michael Powe

Hello,

I want to bind a list box to a collection that will be pulled
dynamically from a web service.

The data that will be pulled will consist of a name and id. I want my
listbox to display the name but, when a name is selected, pass the id
as the value.

i've read and googled but i can't seem to find a straightforward way
to do this. in asp.net, apparently, i could do this with the
ListItems array, but that collection does not exist for a Windows
form.

How can I accomplish my objective in the most direct manner?

Thanks.

mp
 
Hi Michael,

Create a List of KeyValuePairs with items from the web service, with ID being the key and Name the value (or opposite). Use this list as a DataSource for the ListBox and set the ListBox.DisplayMember property to "Value" and ListBox.ValueMember to "Value" (or opposite). The name should be shown in the listbox, and SelectedValue will be the ID.

Roughly something like

List<KeyValuePair<int, string>> list = GetListFromWeb();
listBox1.DataSource = list;
listBox1.DisplayMember = "Value";
listBox1.ValueMember = "Key";
 

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

Back
Top