2016-10-10 48 views
3

是否可以阻止重复记录,还可以编辑选定的记录?我正在处理类似的事情。 Example被阻止编辑DataGridView记录

当我有很多记录,并且更新第二或第三个记录时,每当我尝试使用第一个记录的ID时,我都会发出警告;这很好用。但是,每当我尝试编辑第一条记录的名称,城市等时,弹出重复的ID错误,因为我没有更改ID;它将自己视为重复。不知道该怎么做。我尝试使用断点,但我没有看到任何有趣的事情。谢谢。

private void btnUpdate_Click(object sender, EventArgs e) 
    { 
     if (dgvProfiles.SelectedCells.Count <= 0) 
     { 
      MessageBox.Show("No record was selected to update."); 
     } 

     else { 
      for (int row = 0; row < dgvProfiles.Rows.Count; row++) 
      { 
       for (int col = 0; col < dgvProfiles.Columns.Count; col++) 
       { 
        if (dgvProfiles.Rows[row].Cells[col].Value != null && 
         dgvProfiles.Rows[row].Cells[col].Value.Equals(txtEmail.Text.Trim())) 
        { 
         MessageBox.Show("Duplicate email was entered."); 
         return; 
        } 

        else if (dgvProfiles.Rows[row].Cells[col].Value != null && 
         dgvProfiles.Rows[row].Cells[col].Value.Equals(txtID.Text.Trim())) 
        { 
         MessageBox.Show("Duplicate ID was entered."); 
         return; 

        } 
       } 
      } 
      DataGridViewRow newDataRow = dgvProfiles.Rows[indexRow]; 
      newDataRow.Cells[0].Value = txtID.Text; 
      newDataRow.Cells[1].Value = txtName.Text; 
      newDataRow.Cells[4].Value = txtEmail.Text; 
      newDataRow.Cells[5].Value = txtCity.Text; 
      newDataRow.Cells[6].Value = cbxState.Text; 

     } 
    } 
+1

不是您的实际问题的答案,但您不需要搜索每一行的每一列 - 您知道Id在第零列中,因此只需检查该列中的单元格,并且相同的电子邮件。就目前而言,如果_any cell_与ID值相匹配,则它会被视为重复项。 – stuartd

+1

似乎你应该只是在添加时检查身份验证模式(并且不清楚它们来自哪里)。 – Plutonix

回答