首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# DataGridView 常用操作技巧:資料驗證與提交(五)

     編輯:關於C語言

補充兩項實用技巧:儲存格層級驗證與將編輯資料批次寫回 DataSet。

17. 儲存格驗證

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;
        }
    }
}

18. 資料提交至 DataSet

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 排除新增列。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved