C # - DataGridView cannot add row?

I have a simple C # Windows Forms application that should display a DataGridView. I used Object as the DataBinding (I chose the Car class), and it looks like this:

class Car { public string color { get; set ; } public int maxspeed { get; set; } public Car (string color, int maxspeed) { this.color = color; this.maxspeed = maxspeed; } } 

However, when I set the DataGridView property of AllowUserToAddRows to true , there is still little *, which allows me to add rows.

Someone suggested setting carBindingSource.AllowAdd to true , however, when I do this, I get a MissingMethodException that says my constructor was not found.

+7
source share
3 answers

Your Car class should have a parameterless constructor and your data source should be something like a BindingList

Change the Car class to this:

 class Car { public string color { get; set ; } public int maxspeed { get; set; } public Car() { } public Car (string color, int maxspeed) { this.color = color; this.maxspeed = maxspeed; } } 

And then bind something like this:

 BindingList<Car> carList = new BindingList<Car>(); dataGridView1.DataSource = carList; 

You can also use BindingSource for this, you do not have to, but BindingSource provides some additional functions that may sometimes be needed.


If for some reason you absolutely cannot add a constructor without parameters, you can handle adding a new binding source event and call the constructor parameterized by Car:

Binding Setting:

 BindingList<Car> carList = new BindingList<Car>(); BindingSource bs = new BindingSource(); bs.DataSource = carList; bs.AddingNew += new AddingNewEventHandler(bindingSource_AddingNew); bs.AllowNew = true; dataGridView1.DataSource = bs; 

And the handler code:

 void bindingSource_AddingNew(object sender, AddingNewEventArgs e) { e.NewObject = new Car("",0); } 
+7
source

You need to add the AddingNew event handler:

 public partial class Form1 : Form { private BindingSource carBindingSource = new BindingSource(); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { dataGridView1.DataSource = carBindingSource; this.carBindingSource.AddingNew += new AddingNewEventHandler(carBindingSource_AddingNew); carBindingSource.AllowNew = true; } void carBindingSource_AddingNew(object sender, AddingNewEventArgs e) { e.NewObject = new Car(); } } 
+2
source

I recently discovered that if you implement your own binding list using an IBindingList , you MUST return true in your SupportsChangeNotification in addition to AllowNew .

The MSDN article for DataGridView.AllowUserToAddRows indicates only the following note:

If the DataGridView is bound to data, the user is allowed to add rows if this property and data source have the IBindingList.AllowNew property set to true.

+1
source

All Articles