DataGridView验证单元格非空和主键唯一{转}

来源:互联网 发布:手机在线拼图软件 编辑:程序博客网 时间:2024/06/06 19:28

 

在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 会阻止您退出。在该单元格中键入非空字符串后,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

原创粉丝点击