Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding collections to DataGridView in Windows Forms

I'm trying to bind a collection to a DataGridView. As it turns out it's impossible for the user to edit anything in this DataGridView although EditMode is set to EditOnKeystrokeOrF2.
Here is the simplified code:

public Supplies()
{
   InitializeComponent();
   List<string> l = new <string>();
   l.Add("hello");
   this.SuppliesDataGridView.DataSource = l;
}

It also doesn't work when I change the collection type to SortableBindingList, Dictionary or even use a BindingSource.

What can be wrong here?

like image 368
Sergey Avatar asked Apr 25 '10 12:04

Sergey


1 Answers

For me the following method works as expected:

  • Open your form (usercontrol, etc.) with the designer
  • Add a BindingSource to your form
  • Select the BindingSource in your form and open the properties page
  • Select the DataSource property and click on the down arrow
  • Click on Add project data source
  • Select Object
  • Select the object type you wish to handle
    • This should be the type that will be handled by your collection, not the CustomCollection itself!
  • Show the available data sources by selecting from the MenuBar Data - Show Data Sources
  • Drag and Drop your ItemType from the DatasSources on your form
  • Go into the code of your form and bind your CustomCollection to the BindingSource

        var cc = new CustomCollection();
        bindingSource1.DataSource = cc;
    

Remarks:
The DataGridView is just the last part in your chain to (dis)allow changing, adding and removing objects from your list (or CustomCollection). There is also a property AllowNew within the BindingSource and the ICollection interface has a property IsReadOnly which must be set to false to allow editing. Last but not least, the properties of your class within the collection must have a public setter method to allow changing of a value.

like image 195
Oliver Avatar answered Nov 14 '22 21:11

Oliver