Tim

Tim

  • NA
  • 1
  • 0

DataBinding - Hardcoding DisplayMember and ValueMember

Jan 25 2006 10:29 AM
Something that always bugged me about data binding in Visual Studio is that you specify the DisplayMember and ValueMember of the binding to be strings that are *supposed* to be properties of the data source.  You get no intellisense help when entering these values and, if you spell it wrong or the name of a property changes later, the project still compiles and runs fine until you hit that binding.

Is there a way, using reflection or any other method that I am not clear on, to get the name of a property directly from an object instance?  For example, I have a 'Customer' class with a 'Name' property (string) that I want to bind to a text box (txtName).  The code I'd normally use to do this is:

Customer customer = new Customer();
txtName.DataBindings.Add("Text", customer, "Name");

What I would like to do is avoid hardcoding the "Name" string and do something kind of like this (even though I know this doesn't work, it is just a concept):

Customer customer = new Customer();
txtName.DataBindings.Add("Text", customer, customer.Name.PropertyName);

'PropertyName' would return the name of the property in question, in this case, "Name".  If the 'Name' property were to change to 'CustomerName' in the Customer class, then my version would not compile because 'customer.Name' does not exist, while the original version with 'Name' hardcoded would still compile and then fail on the binding.  So how can I get the property name of a property without hardcoding the name of said property as a string in the call?

I hope my inquiry makes sense, I look forward to hearing any of your advice and opinions on this matter.