views:

129

answers:

3

I'm trying to bing collection to DataGridView. As it turns out it's impossible for 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 collection type to SortableBindingList, Dictionary or even use BindingSource.

What can be wrong here?

A: 
Jamie Dixon
There is no such method in SuppliesDataGridView.
Sergey
A: 

Try this:

    public class CustomCollection { public string Value { get; set; } }

    public Supplies()
    {
        InitializeComponent();
        List<CustomCollection> l = new List<CustomCollection> { new CustomCollection { Value = "hello" } };
        this.SuppliesDataGridView.DataSource = l;
    }
Jacob Seleznev
+1  A: 

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.

Oliver