datagridview验证新添加的一行是否存在(根据某一列检索)

该方法能实现验证当前新添加的一行的某一列的值在表格中是否存在,如果存在,则提示并将焦点停在改单元格上以备修改。

public void xDataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
//首先停止编辑表格
_frmaddnewfitting.xDataGridView1.EndEdit();
int rowindex = e.RowIndex;
int columnindex = e.ColumnIndex;
if (columnindex == 0)
{
//判断当前单元格的内容不为空
if(_frmaddnewfitting.xDataGridView1.CurrentCell.Value != null)
{
string columnname = _frmaddnewfitting.xDataGridView1.CurrentCell.Value.ToString();
//遍历当前表格
foreach (DataGridViewRow row in _frmaddnewfitting.xDataGridView1.Rows)
{
int acturalRowCount = _frmaddnewfitting.xDataGridView1.Rows.Count - 1;//表格中的实际行数
if (row.Cells["ClmName"].RowIndex != acturalRowCount && rowindex != row.Cells["ClmName"].RowIndex && columnindex == row.Cells["ClmName"].ColumnIndex)
{
if (columnname == row.Cells["ClmName"].Value.ToString())
{
MessageBox.Show("已存在列名:" + columnname , "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
e.Cancel = true;
}
}
}
}
else
{
MessageBox.Show("列名不能为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
e.Cancel = true;
}
}
}

posted on 2012-02-18 11:42  折翼的天使  阅读(431)  评论(0编辑  收藏  举报