验证datagridview中的单元格

时间:2013-09-27 22:18:46

标签: c# winforms validation datagridview

我在Windows窗体中有一个DataGridView,它有2列,最后一列将包含数据包的名称,重点是该名称永远不必重复。

我使用CellValidating事件尝试使用此代码

        string value = Convert.ToString(dgvTiendas.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
        int cellIndex = e.RowIndex;

    if(cellIndex == 1)
    {
            foreach (DataGridViewRow rw in dgvTiendas.Rows)
            {
                if (cellIndex == rw.Index)
                {
                    return;
                }
                else
                {
                    string valorRow = Convert.ToString(rw.Cells["ContenedorCodigoBarras"].Value);
                    if (value == valorRow)
                    {
                        MessageBox.Show("The container is already used");
                        dgvTiendas.Rows[e.RowIndex].ErrorText = "Contenedor ya utilizado";
                        e.Cancel = true;
                    }
                    else
                    {
                        e.Cancel = false;
                    }
                }
            }
    }

当我运行应用程序并编写容器名称时,它已经过验证,但似乎验证了当前单元格,因为RowHeader上出现“错误文本”。

请帮我几个星期。

1 个答案:

答案 0 :(得分:0)

您遇到此问题,因为您正在使用此代码设置行的错误文本。

dgvTiendas.Rows[e.RowIndex].ErrorText = "Contenedor ya utilizado";

您需要设置单元格的错误文本

dgvTiendas[e.ColumnIndex, e.RowIndex].ErrorText = "an error occured";
相关问题