DataGridView驗證儲存格非空和主鍵唯一{轉}

來源:互聯網
上載者:User

 

在datagridview的 CellValidating事件中驗證輸入的資料是否符合自己的要求比如要驗證資料為空白時

private void dataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
// Validate the CompanyName entry by disallowing empty strings.
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;
}
}
}

void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
// Clear the row error in case the user presses ESC.
dataGridView1.Rows[e.RowIndex].ErrorText = String.Empty;
}

上面這段代碼的作用就是
雙擊 CompanyName 列中的儲存格時,可以編輯該值。如果刪除所有字元,並按 Tab 鍵退出該儲存格,則 DataGridView 會阻止您退出。在該儲存格中鍵入非Null 字元串後,DataGridView 控制項將允許您退出此儲存格

private void dataGridView1_DataError(object sender,
DataGridViewDataErrorEventArgs e)
{
// If the data source raises an exception when a cell value is
// commited, display an error message.
if (e.Exception != null &&
e.Context == DataGridViewDataErrorContexts.Commit)
{
MessageBox.Show("CustomerID value must be unique.");
}
}
上面這段代碼的作用是

如果為 CustomerID 輸入重複的值並提交編輯結果,則該儲存格的值將自動回復為原來的值,您將看到一個顯示資料輸入錯誤的 MessageBox

來自:http://hi.baidu.com/sghcz_lv/blog/item/3fd9197f4202480f28388a21.html

具體的驗證其實一個事件就可以解決,不信你可以看我另外一片文章:

http://hi.baidu.com/fxb%5Fhyb/blog/item/146372237f216446925807d1.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.