Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Databinding and refactoring code [closed]

I'm just curious about some coding practice behind binding data to a combobox (or other bindable object I guess). Let's say I've created an object, and I want to add a bunch of them to a combobox. So I create my object and give it some properties.

public class ObjectForList
{
    public string ObjectName { get; set; }
    public int ObjectID { get; set; }
    public string SomeOtherProperty { get; set; }
    public ObjectForList()
    {
    }
}

So then I make a list of them and set it as the source for my combo box

List<ObjectForList> myObjects= new List<ObjectForList> { ...bunch of ObjectForList objects...};

comboBox1.DataSource = myObjects;
comboBox1.DisplayMember = "ObjectName";
comboBox1.ValueMember = "ObjectID";

That's how I understand it's supposed to be done at least. I see that implementation on all the explanations I've found on the net.

But having the Display and Value Members as hard coded strings of the variable names seems uneasy to me. If someone comes along in Visual Studio years later and refactors the ObjectID property (to be "MyID" or something), then the combobox binding would break. And it would still compile, so no one would notice until loading the form with the combobox on it. As well, you wouldn't be able to find uses of that property using 'Find References' since it's just a string.

What do people think about this? How do use this and still keep your code maintainable?

like image 852
Luke Avatar asked Jul 24 '26 17:07

Luke


1 Answers

Can be done without passing member type as well right ?

  comboBox1.ValueMember = GetPropName(() => ObjectForListObject.ObjectID);

  public static string GetPropName<T>(Expression<Func<T>> propExp)
  {
     return (propExp.Body as MemberExpression).Member.Name;
  }
like image 55
warrior Avatar answered Jul 27 '26 05:07

warrior