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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With