If you want to create a truly general function, you can calculate a little:
Suppose you have two comboboxes, one of which contains elements based on user collection A with DisplayMember AA, and the other contains elements based on user collection B with DisplayMember BB:
How can a common function know what value needs to be returned? Based on DisplayMember, of course, but you donβt want to pass AA / BB into a common function if you want it to be common.
So,
[anItemTheCombobox.GetType().GetProperty(theCombobox.DisplayMember).GetValue(theCombobox, null)]
Background
I used it in a generic function called calculateAndSetWidth. The function checks all the elements in the list to determine maxWidth:
public void calculateAndSetWidth(ListBox listbox, int minWidth = 0) { Graphics graphics = this.CreateGraphics(); int maxWidth = 0; SizeF mySize = null; foreach (object item in listbox.Items) { mySize = graphics.MeasureString(item.GetType().GetProperty(listbox.DisplayMember).GetValue(item, null), listbox.Font); if (mySize.Width > maxWidth) { maxWidth = mySize.Width; } } listbox.Width = Math.Max(maxWidth, minWidth);
}
source share