我想检查在数据网格视图中输入的值是否已存在

本文关键字:输入 是否 存在 视图 检查 数据 网格 数据网 | 更新日期: 2023-09-27 18:33:51

我正在尝试验证我的数据网格视图。 当我在一行中添加一些数据时,如果我在另一行中输入一些数据,那么它应该会显示一条消息。我正在尝试以下代码。引发空异常错误。由于特定单元格中的值为空。它无法获取值。

private void dataGridViewBrandDetails_CellLeave(object sender, DataGridViewCellEventArgs e)
    {
                    if (e.ColumnIndex == 0 && e.RowIndex > -1)
        {
        var dgv = sender as DataGridView;
   for (int i = 0; i < dataGridViewBrandDetails.Rows.Count; i++)
       {

            string s = dgv[e.ColumnIndex, e.RowIndex].Value.ToString();
           if (dataGridViewBrandDetails.Rows[i].Cells[0].Value != null && dataGridViewBrandDetails.Rows[e.RowIndex].Cells[0].Value.ToString() == dataGridViewBrandDetails.Rows[i].Cells[0].Value.ToString())
            {
                MessageBox.Show("The value already existed in DataGridView.");

            }
        }   
        }
    } 

我想检查在数据网格视图中输入的值是否已存在

更改一些内容:

private void dataGridViewBrandDetails_CellLeave(object sender, DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex == 0 && e.RowIndex > -1)
        {
        var dgv = sender as DataGridView;
        string s = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
        for (int i = 0; i < dataGridViewBrandDetails.Rows.Count; i++)
        {
           if(i!=e.RowIndex) // To skip the row with newly inserted value
           {
               if (dataGridViewBrandDetails.Rows[i].Cells[0] != null && dataGridViewBrandDetails.Rows[i].Cells[0].Value.ToString() == s
               {
                   MessageBox.Show("The value already existed in DataGridView.");
               }
            }
        }   
        }
    }

我保留了您的代码,几乎没有更改。尽管您可能要执行的更改很少。第一:如果你的第一行是标题行而不是有值的行,则使 i=1。第二:如果第 0 列的行包含控件,则应将它们强制转换为控件,然后读取其值。