I have a simple C# Windows Forms application which should display a DataGridView. As DataBinding I used an Object (selected a class called Car) and this is what it looks like:
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 AllowUserToAddRows
to true
, there is still no little * which allows me to add rows.
Someone suggested to set carBindingSource.AllowAdd
to true
, however, when I do that, I get a MissingMethodException
which says my constructor could not be found.
Your Car class needs to have a parameterless constructor and your datasource needs 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 a BindingSource for this, you don't have to but BindingSource gives some extra functionality that can sometimes be necessary.
If for some reason you absolutely cannot add the parameterless constructor then you can handle the adding new event of the binding source and call the Car parameterised constructor:
Setting up the binding:
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With