Joe Schrag
Joe Schrag

Reputation: 865

Is it a bad idea to use the comboBox.DisplayMember & ValueMember properties?

I'm adding a combobox to a WinForms application, I came across the DisplayMember & ValueMember properties. Their functionality is exactly what I need in my application, but I'm not sure I like the way they work.

comboBox.Items.Add(myObj);
comboBox.DisplayMember = "Name";
comboBox.ValueMember = "Id";

In the code above my object is the actual "Item", and it's name & Id properties will be used for displayed text & selected value respectively. The thing I'm unsure of is the hard coded "Name" & "Id" being passed into those properties. That is something not checked at compile time. So, if I ever changed my object.Name property to object.FullName, this code would break at runtime.

I've thought about getting the property name dynamically (as asked here: get name of a variable or parameter), but that feels very wrong.

So, is it ill-advised to use these properties? If so, what is the recommended way to store my object as the combobox item?

Upvotes: 2

Views: 403

Answers (2)

Patrick Hofman
Patrick Hofman

Reputation: 156978

That is perfectly fine to use them.

For your concern of compile-time checks: in the next version of C# there is a nameof operator, comparable to the typeof there is now already.

You could use it like this:

comboBox.DisplayMember = nameof(obj.Name);

There are solutions already there to get a similar result.

Upvotes: 2

Michael Gunter
Michael Gunter

Reputation: 12811

This sort of loose-coupling between model/viewmodel and view is actually becoming more and more common. XAML's binding (used in WPF, Silverlight, Windows Phone, etc) works in a very similar fashion. There are techniques you can use to force the XAML designers to provide some feedback (http://msdn.microsoft.com/en-us/library/ff602274.aspx), but these don't break the compile. Accept it!

Upvotes: 2

Related Questions