当应用程序填充新添加的行的默认值时,可以更方便地输入数据。 通过DataGridView类,你可以用DefaultValuesNeeded事件填充默认值。 当用户为新记录输入行时,将引发此事件。 当代码处理此事件时,可以使用选择的值填充所需的单元格。
下面的代码示例演示如何使用 DefaultValuesNeeded 事件为新行指定默认值。
示例:
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["Country"].Value = "USA";
e.Row.Cells["CustomerID"].Value = NewCustomerId();
}
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("Country").Value = "USA"
.Cells("CustomerID").Value = NewCustomerId()
End With
End Sub
编译代码
此示例需要:
名为 DataGridView 的
dataGridView1
控件。用于生成
NewCustomerId
唯一CustomerID
值的函数。对 System 和 System.Windows.Forms 程序集的引用。