Sergey
Sergey

Reputation: 49788

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?

Upvotes: 5

Views: 10076

Answers (3)

Oliver
Oliver

Reputation: 45119

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.

Upvotes: 5

Jacob Seleznev
Jacob Seleznev

Reputation: 8141

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;
    }

Upvotes: 2

Jamie Dixon
Jamie Dixon

Reputation: 54011

Once you've set the DataSource property you'll then want to fire off the DataBind() method.

this.SuppliesDataGridView.DataSource = l;
this.SuppliesDataGridView.DataBind();

UPDATE:

As you rightly pointed out in the comments, the DataBind() method doesn't exist for this control.

This link might provide some helpful information: http://msdn.microsoft.com/en-us/library/fbk67b6z%28v=VS.90%29.aspx

Upvotes: 0

Related Questions