If you have a binding source to your DataGridView, you can call EndCurrentEdit()
in the DefaultValuesNeeeded
event handler to commit the new row immediately with the default values.
{
dt = new DataTable();
dt.Columns.Add("Cat");
dt.Columns.Add("Dog");
dataGridView1.AllowUserToAddRows = true;
dataGridView1.DefaultValuesNeeded += dataGridView1_DefaultValuesNeeded;
dataGridView1.DataSource = dt;
}
void dataGridView1_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
{
var dgv = sender as DataGridView;
if(dgv == null)
return;
e.Row.Cells["Cat"].Value = "Meow";
e.Row.Cells["Dog"].Value = "Woof";
// This line will commit the new line to the binding source
dgv.BindingContext[dgv.DataSource].EndCurrentEdit();
}
If you don't have a binding source, we cannot using the DefaultValuesNeeded
event since it doesn't work. But we can simulated it by capturing the CellEnter
event.
{
dataGridView1.Columns.Add("Cat", "Cat");
dataGridView1.Columns.Add("Dog", "Dog");
dataGridView1.AllowUserToAddRows = true;
dataGridView1.CellEnter += dataGridView1_CellEnter;
}
void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
var dgv = sender as DataGridView;
if (dgv == null)
return;
var row = dgv.Rows[e.RowIndex];
if (row.IsNewRow)
{
// Set your default values here
row.Cells["Cat"].Value = "Meow";
row.Cells["Dog"].Value = "Woof";
// Force the DGV to add the new row by marking it dirty
dgv.NotifyCurrentCellDirty(true);
}
}