Hello
In my windows form application, I have a datagridview with four columns. my datagridview is NOT bound to a data source. but it reads data from different application during the runtime.
How to prevent adding new rows during the run time if the Patient ID is already exist in the table?
Example:
PatientID PatientName Gender Age
Abcd1234 xxxxxx xxxxxx xxxxxx
FIxIlm568 xxxxxx xxxxxx xxxxxx
na7a5419 xxxxxx xxxxxx xxxxxx
If for example the patientId found twice on the list, then the datagridview will not add another row with that patientID. the new row will be deleted automatically (if the patientID got duplicated).
Can you help me on this, plz?

Pankaj Kumar ChoudharyRank #80 · 24.4K reputationPosted May 31, 2015, 8:46 PM EDT
List<string> list =newList<string>();02for(inti = 0; i < dataGridView1.Rows.Count; i++ )03{04stringstr = dataGridView1.Rows[i].Cells[0].Value.ToString();05if(!list.Contains(str))06list.Add(dataGridView1.Rows[i].Cells[0].Value.ToString());07else08{09dataGridView1.Rows.Remove(dataGridView1.Rows[i]);10}1112}Dipankar BiswasRank #992 · 2K reputationPosted May 31, 2015, 8:30 PM EDT
Syed ShanuRank #87 · 23.7K reputationPosted May 31, 2015, 8:35 PM EDT
Hi,
You can remove the duplicate record from DataTable before you set the datasource of Datagrid view.
Vipin Saxena162 reputationPosted Feb 19, 2018, 11:39 PM EST
Jiyaul MustaphaRank #5,573 · 294 reputationPosted Jul 24, 2019, 11:59 PM EDT
{
for (int ThisRow = 0; ThisRow < GridView2.Rows.Count - 1; ThisRow++)
{
Label lbl_Code = (Label)GridView2.Rows[ThisRow].FindControl("lblCode");
lblCode.Value = lbl_Code.Text;
GridViewRow CompareRow = GridView2.Rows[ThisRow];
for (int NextRow = ThisRow + 1; NextRow < GridView2.Rows.Count; NextRow++)
{
GridViewRow row = GridView2.Rows[NextRow];
bool DuplicateRow = true;
Label lbl_Code1 = (Label)GridView2.Rows[NextRow].FindControl("lblCode");
hidnxtrowCode.Value = lbl_Code1.Text;
if ((lblCode.Value) == (hidnxtrowCode.Value))
{
row.Cells[1].Text = "";
row.Cells[2].Text = "";
}
else if (DuplicateRow)
{
DuplicateRow = false;
}
}
}
}