WinForms Unpacking Linking

Imagine these two classes:

class Part
{
 public string Name { get; set;}
 public int Id { get; set; }
}

class MainClass
{
 public Part APart { get; set;}
}

How to associate MainClass with a combo box in WinForm, so it displays Part.Name ( DisplayMember = "Name";), and the selected combo element sets the APart property in MainClass without having to handle any events on the popup.

As far as I know, setting ValueMember from ComboBox to "Id" means that it will try to set APart to a number (Id) which is not correct.

Hope this is clear enough!

+5
source share
4 answers

, , ValueMember (= ComboBox.SelectedItem) , DisplayMember - , ? , , ComboBox , - , ValueMember DisplayMember.

, ( Part -):

  • `ToString()` `Part`, ` Name`. "ComboBox`` ValueMember` ` `APart`` " DisplayMember "null. (Untested, )
  • , . "ValueMember" "DisplayMember" "Name". , .
  • getter setter. , `APart` , ` MainClass` `Part`, ` Id` (`int`) ` Part`. (, , ComboBox.)
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");
    }
}
+1

, , .
, .

0

ValueMember null, (.. Part) . DisplayMember "Name".

0

"" . System.ComponentModel.INotifyPropertyChanged , - :

private String _SelectedPart = String.Empty; 

public String SelectedPart 
{
   get  
   {   
      return _SelectedPart;   
   }  
   set   
   {            
      if (_SelectedPart != value)  
      {
         _SelectedPart  = value;   

         // helper method for handing the INotifyPropertyChanged event
         PropertyHasChanged(); 
      }
   }
}

"ObjectDataSource" (Shift-Alt-D VS2008 ), ComboBox :

DataSource, ObjectDataSource "BindingSource", . DisplayMember, Name ValueMember, DataBindings.SelectedValue, SelectedPart "BindingSource".

I know that the above sounds are complex, and it may take a little to find all the parts that I just described (I want to give you a tutorial or a screenshot), but in fact it is very quick to do as soon as you get used to it .

This, by the way, is considered "data binding" in .NET, and there are some good tutorials that can give you more information.

0
source

All Articles