Imagine these two classes:
class Part
{
public string Name { get; set;}
public int Id { get; set; }
}
class MainClass
{
public Part APart { get; set;}
}
How can I bind MainClass to a combo box on a WinForm, so it displays Part.Name (DisplayMember = "Name";
) and the selected item of the combo sets the APart property of the MainClass without the need to handle any events on the dropdown.
As far as I know, setting ValueMember of the ComboBox to "Id" means that it will try to set APart to a number (Id) which is not right.
Hope this is clear enough!
What you're looking for is to have the ValueMember
(= ComboBox.SelectedItem
) be a reference to the object itself, while DisplayMember
is a single property of the item, correct? As far as I know, there's no good way to do this without creating your own ComboBox
and doing the binding yourself, due to the way ValueMember
and DisplayMember
work.
But, here's a couple things you can try (assuming you have a collection of Part
s somewhere):
Part _APart;
object APart
{
get {return _APart;}
set {
if(value is int)
_APart = MyPartCollection.Where(p=>p.Id==value).Single();
else if(value is Part)
_APart = value;
else
throw new ArgumentException("Invalid type for APart");
}
}
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