views:

389

answers:

6

The question is asked with respect to an Object DataSource. So Consider that I have a class

public class Customer{

    public String name;
    public int age;

    public Customer(String name, int age) {
         this.name = name;
         this.age = age;
    }
}

And I have databound a list box to a list of these objects. So I say

listBox.DisplayMember = "name";

But my question is that when I refactor my Customer class's name to

public String fullName;

the DisplayMember still stays at "name". This will fail. So it decreases my ability to refactor domain objects. Is there any way around for this?

A: 

This is why you should use properties rather than public fields to expose data from your classes. You can more easily refactor the inner working without breaking too much. Although there of course will be instances where you might have to break something.

Conrad
How is this related?
Xinxua
A: 

ReSharper can do this for you ... try to get it - a really great piece of software. Probably CodeRush can do it, too. But I am not sure.

tanascius
+1  A: 

The only way i have found around this is to use extra properties on the objects so have a

string DisplayMember
{
    get { return 'name'; }
}

and when you refactor your object you then only need to change the returned string to your new property name making it a change in one location rather than in a few.

It's not great but works better than hardcoding in the app!

HTH

OneSHOT

OneSHOT
Good idea and simple to implement, +1. Obviously not perfect but as you said, better than hardcoding everywhere in the app.
Meta-Knight
A: 

About the only real way I have found to "get around" this "issue", would be to add a new public, ReadOnly property. Name that property "ListDisplay" or something similar. Then you can modify the implementation without any impact to the UI.

It isn't an ideal situation, but it works.

Mitchel Sellers
+1  A: 

If you leave the DisplyMember empty then the ListBox will use the default ToString(). When you override this function in your class, the listbox will show the appropiate value. Then if you change the name of the field, your build will break in the ToString() function.

Jorg Visch
+2  A: 

This is a sexier and more flexible solution

Snippet...

To make a long story short, instead of writing:

textBoxCustomerName.DataBindings.Add("Text", bindingSource, "CustomerName");

my suggestion is to write something like:

dataSource.CreateBinding(textBoxCustomerName, ctl => ctl.Text, data => data.Name);

This way, your code will still run without any problems when you refactor your entities (let’s say, if you rename the customer’s Name property to CompanyName).

Pretty sweet eh?

Also some solutions are here http://stackoverflow.com/questions/1329138/how-to-make-databinding-type-safe-and-support-refactoring/1334951

Allen