補充兩項實用技巧:儲存格層級驗證與將編輯資料批次寫回 DataSet。
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) {
if (dataGridView1.Columns[e.ColumnIndex].Name == "CompanyName") {
if (string.IsNullOrEmpty(e.FormattedValue.ToString())) {
dataGridView1.Rows[e.RowIndex].ErrorText = "Company Name must not be empty";
e.Cancel = true;
}
}
}
DataSet ds = new DataSet("MyDataSet");
ds.Tables[tableName].Rows.Clear();
try {
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++) {
DataRow row = ds.Tables[tableName].NewRow();
for (int j = 0; j < dataGridView1.Columns.Count; j++)
row[j] = Convert.ToString(dataGridView1.Rows[i].Cells[j].Value);
ds.Tables[tableName].Rows.Add(row);
}
} catch { MessageBox.Show("輸入類型錯誤!"); }
注意:迴圈上限 Rows.Count - 1 排除新增列。