如何在c#中插入datagridview时检查重复的行?

时间:2018-03-17 05:00:22

标签: c# datagridview

我想在插入行时检查DatagridView中的整行是否重复。如果一行重复,则给出错误消息,否则将整行添加到DatagridView。让我知道解决方案或任何替代方案。 感谢。

//This is my sample code:I know this code is wrong
List<string> listUserID = new List<string>();
List<string> listPlantID = new List<string>();
for (int i = 0; i < dgvTableInfo.Rows.Count - 1; i++)
{
   string UserID = dgvTableInfo.Rows[i].Cells["UserID"].Value.ToString();
   string PlantName = dgvTableInfo.Rows[i].Cells["PlantID"].Value.ToString();
   if ((!listUserID.Contains(UserID, StringComparer.OrdinalIgnoreCase)) || (!listPlantID.Contains(PlantName, StringComparer.OrdinalIgnoreCase)))
   {
      listUserID.Add(dgvTableInfo.Rows[i].Cells["UserID"].Value.ToString());
      listPlantID.Add(dgvTableInfo.Rows[i].Cells["PlantID"].Value.ToString());
   }
   else
   {
      GESDialogBox.Show(this, @"User with same userid and plantid is already exist, please choose unique userid and plantid ", MessageBoxButtons.OK, MessageBoxIcon.Error);
      return;
    }
}

datagridview

1 个答案:

答案 0 :(得分:0)

有很多种方法,一种简单的方法是保留一个单独的密钥集合,并检查它。例如,见下文。

        var keys = new List<string>();

        for (int i = 0; i < dgvTableInfo.Rows.Count - 1; i++)
        {
            var userID = dgvTableInfo.Rows[i].Cells["UserID"].Value.ToString();
            var plantName = dgvTableInfo.Rows[i].Cells["PlantID"].Value.ToString();
            var key = userID + plantName;

            if (!keys.Contains(key))
            {
                keys.Add(key);
            }                
            else
            {
                GESDialogBox.Show(this, @"User with same userid and plantid is already exist, please choose unique userid and plantid ", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }