Compartir a través de


How to: Specify Default Values for New Rows in the Windows Forms DataGridView Control

You can make data entry more convenient when the application fills in default values for newly added rows. With the DataGridView class, you can fill in default values with the DefaultValuesNeeded event. This event is raised when the user enters the row for new records. When your code handles this event, you can populate desired cells with values of your choosing.

The following code example demonstrates how to specify default values for new rows using the DefaultValuesNeeded event.

Example

Private Sub dataGridView1_DefaultValuesNeeded(ByVal sender As Object, _
    ByVal e As System.Windows.Forms.DataGridViewRowEventArgs) _
    Handles dataGridView1.DefaultValuesNeeded

    With e.Row
        .Cells("Region").Value = "WA"
        .Cells("City").Value = "Redmond"
        .Cells("PostalCode").Value = "98052-6399"
        .Cells("Region").Value = "NA"
        .Cells("Country").Value = "USA"
        .Cells("CustomerID").Value = NewCustomerId()
    End With

End Sub
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();
}

Compiling the Code

This example requires:

  • A DataGridView control named dataGridView1.

  • A NewCustomerId function for generating unique CustomerID values.

  • References to the System and System.Windows.Forms assemblies.

See Also

Reference

DataGridView
System.Windows.Forms.DataGridView.DefaultValuesNeeded

Concepts

Using the Row for New Records in the Windows Forms DataGridView Control

Other Resources

Data Entry in the Windows Forms DataGridView Control