Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropdown binding in WinForms

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!

like image 541
Khash Avatar asked Nov 15 '22 16:11

Khash


1 Answers

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 Parts somewhere):

  1. Override the `ToString()` method of `Part` to return the `Name` property. Then set your `ComboBox`'s `ValueMember` to `"APart"` and leave `DisplayMember` null. (Untested, so no guarantees)
  2. You can create a new property in Part to return a reference to itself. Set the 'ValueMember' to the new property and 'DisplayMember' to `"Name"`. It may feel like a bit of a hack, but it should work.
  3. Do funny things with your `APart` getter and setter. You'll lose some strong-typing, but if you make `APart` an object and `MainClass` contains the collection of `Part`s, you can set it by `Id` (`int`) or `Part`. (Obviously you'll want to be setting it by Id when you bind the ComboBox to it.)
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");
    }
}
like image 106
lc. Avatar answered Dec 10 '22 11:12

lc.