2

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?

Community
  • 1
  • 1
Joe Schrag
  • 855
  • 8
  • 23
  • Not ill-advised. Its exactly how they were designed to be used. – crthompson Apr 14 '14 at 21:48
  • Ok. What about the fact that this will not be checked at compile time? Am I making that out to be a bigger problem than it really is? – Joe Schrag Apr 14 '14 at 21:54
  • 1
    No, that is a valid concern. I know that i've seen some libraries that will allow you to do compile time checks, but the combobox control has been around for such a long time. – crthompson Apr 14 '14 at 22:07

2 Answers2

2

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!

Michael Gunter
  • 12,528
  • 1
  • 24
  • 58
2

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.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325