Avatar of brettr
brettr

asked on 

Combobox.datasource = List<myobject>?

I have a List<> of myobject.  myobject looks like this:

myobject.UserId
myobject.Name

I assign it to the combox box:

cmbbox.DisplayMember = "UserName";
cmbbox.ValueMember = "UserID";
cmbbox.DataSource = myobjectList;

When I run the app, it always comes through the combobox as namespace.myobject.  How can I get the values to bind correctly?  I've also tried BindingList<> but that didn't make a difference.

Thanks.
C#

Avatar of undefined
Last Comment
twobitbela
Avatar of twobitbela
twobitbela

cmbbox.DisplayMember = "UserName";
may need to be
cmbbox.DisplayMember = "Name";
unless that was a typo of yours in the question only
Avatar of brettr
brettr

ASKER

Sorry, there is a "Name" and "UserName".  It doesn't work for either.
ASKER CERTIFIED SOLUTION
Avatar of twobitbela
twobitbela

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of brettr
brettr

ASKER

In myobject, they attributes were public fields, not properties. Once I changed them to properties, it worked.  Thanks.
Avatar of twobitbela
twobitbela

Ah yes, they do need to be properties.
Avatar of brettr
brettr

ASKER

If I am binding that way and want a single item that is just text and reads "All", how can I do that?

I add it this way:
cmbbox.Items.Add( "All" );

But it never appears.  I'm guessing because it doesn't adhere to the DisplayMember and ValueMember rules.  Do I need to new up a myobject and assign only the Name property than add that?
Avatar of twobitbela
twobitbela

Try
cmbbox.Items.Insert(0, new ListItem("All", "-1"));

Or before you bind it create a dummy MyObject with the name of All and add that to your list.
Avatar of brettr
brettr

ASKER

I like the first option since it doesn't pollute the list.  But isn't ListItem an ASP object?  I'm using this in a winform app.
Avatar of twobitbela
twobitbela

Ah yeah, sorry, that is an asp.net thing.  It's been a long day.  There may be something similiar you can do in winforms, offhand I'm not exactly sure though.
C#
C#

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).

98K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo