private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null) //不能省略,如果省略,单元格编辑时按下esc会报错“未将对象引用设置到对象的实例”
{
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = string.Empty;//输入错误日期格式,如2012-3-99,将其删除但不输入数据,需要取消错误提示
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = string.Empty;
return;
}
if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString().Trim().Length == 0) //只输入空格时,需要取消错误提示
{
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = string.Empty;
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = string.Empty;
return;
}
if (e.ColumnIndex == 0) //日期所在栏位
{
DateTime dtime;
if (DateTime.TryParse(dataGridView1.CurrentCell.EditedFormattedValue.ToString().Trim(), out dtime))
{
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = string.Empty; //如果改正错误,取消单元格提示
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = dtime.ToString("yyyy-M-d");//如果是1/1,则显示2011-1-1 (年份以当前为准)
}
else
{
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "输入内容不符合规范!";
}
}
{
if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null) //不能省略,如果省略,单元格编辑时按下esc会报错“未将对象引用设置到对象的实例”
{
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = string.Empty;//输入错误日期格式,如2012-3-99,将其删除但不输入数据,需要取消错误提示
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = string.Empty;
return;
}
if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString().Trim().Length == 0) //只输入空格时,需要取消错误提示
{
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = string.Empty;
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = string.Empty;
return;
}
if (e.ColumnIndex == 0) //日期所在栏位
{
DateTime dtime;
if (DateTime.TryParse(dataGridView1.CurrentCell.EditedFormattedValue.ToString().Trim(), out dtime))
{
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = string.Empty; //如果改正错误,取消单元格提示
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = dtime.ToString("yyyy-M-d");//如果是1/1,则显示2011-1-1 (年份以当前为准)
}
else
{
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "输入内容不符合规范!";
}
}
}
private void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0)
dataGridView1.CurrentCell.ErrorText = string.Empty; //先取消错误提示
}

本文详细阐述了在数据网格中验证数据有效性并处理错误的方法,包括如何在单元格编辑时检查日期格式、确保输入非空值,并在验证通过后更新数据格式。此过程对于维护数据准确性和用户界面友好性至关重要。
4011

被折叠的 条评论
为什么被折叠?



