Groups | Blog | Home
all groups > c# > november 2007 >

c# : binding a listbox


Michael Powe
11/30/2007 11:27:38 PM
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

--
'cat' is not recognized as an internal or external command,
Morten Wennevik [C# MVP]
12/1/2007 4:09:41 PM
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 Data=
Source for the ListBox and set the ListBox.DisplayMember property to "Va=
lue" 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 =3D GetListFromWeb();
listBox1.DataSource =3D list;
listBox1.DisplayMember =3D "Value";
listBox1.ValueMember =3D "Key";

On Sat, 01 Dec 2007 05:27:38 +0100, Michael Powe <michael+gnus@trollope.=
[quoted text, click to view]



-- =

Happy coding!
AddThis Social Bookmark Button