Tuesday 21 April 2009

New row default values in DataGridView

I was looking for a nice way of displaying default values in a datagridview when a user creates a new row.

At first I looked at settings in the binding source but there wasn't anything that stood out. Then I looked att he table adapter again there wasn't anything I could use.

Finally I found that it was an event in dataGridView that was required. The event is called 'DefaultValuesNeeded'. It can be used to specify default values for any row in a DataGridView. It is fired when you create a new row in a DatagridView.

Below is a C# example from http://msdn.microsoft.com/en-us/library/b22t666e.aspx

private void dataGridView1_DefaultValuesNeeded(object sender,
System.Windows.Forms.DataGridViewRowEventArgs e)
e.Row.Cells["Region"].Value = "WA";
e.Row.Cells["City"].Value = "Redmond";
e.Row.Cells["PostalCode"].Value = "98052-6399";
e.Row.Cells["Region"].Value = "NA";
e.Row.Cells["Country"].Value = "USA";
e.Row.Cells["CustomerID"].Value = NewCustomerId();

Very useful and it is something I will be using a lot.