當應用程式填入新加入資料列的預設值時,可以讓資料輸入更加方便。 使用 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
正在編譯程式碼
這個範例需要:
名為
dataGridView1的 DataGridView 控制項。用於產生唯一
CustomerID值的NewCustomerId函式。System 和 System.Windows.Forms 組件的參考。