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

实现类似于sql server/oracle中新建一个表时,对输入的列的名字的验证。若已存在则提示。我是菜鸟,欢迎各位大神给予指教。

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:47  折翼的天使  阅读(471)  评论(0编辑  收藏  举报