AlgorithNewbie AlgorithNewbie - 4 months ago 23
MySQL Question

Datagrid Remove duplicate rows while Adding

Hi I want to add a value to datagrid when I input videoNo. to text box and click OK this will show :

Enter a VideoNo

This is the output

Output when Click OK

Then when I add the same video again it will duplicate in the datagrid like these:
enter image description here

How Can I avoid this duplication ?
This is my code for adding

private void button2_Click(object sender, EventArgs e)
{
listBox1.Visible = false;
if (txt_vidNo.Text == "")
{
MessageBox.Show("Input Video Number", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

}
else
{
DialogResult dt = MessageBox.Show("Add Video?", "Continue", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

if (dt == DialogResult.Yes)
{

panel4.Visible = true;
con = koneksyon.getConnect();
con.Open();
cmd = new SqlCommand("select * from Stock where videoNo ='" + txt_vidNo.Text + "'", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{

dataGridView1.Rows.Add(dr[0], dr[1], dr[2], dr[3], dr[4], dr[5], dr[6], dr[7], dr[8]);
}
txt_vidNo.Clear();
btn_Rent.Visible = true;
panelPay.Visible = true;
cmd.Dispose();
con.Close();
dr.Dispose();
}
else
{
txt_vidNo.Clear();
}

}
}


What I want is when I input the same value it will not duplicate in Datagrid, How Can I do these?

Answer

You simply have to check if the value of your unique key is already in the datagrid.

You can do that with LINQ where you check all rows with non null values if the value in Column Catalog Number matches the read Catalog number.

while (dr.Read())
{
   if (dataGridView1.Rows.Cast<DataGridViewRow>().Where(row => row.Cells[0].Value != null).All(row => (int) row.Cells[0].Value != dr[0]))
      dataGridView1.Rows.Add(dr[0], dr[1], dr[2], dr[3], dr[4], dr[5], dr[6], dr[7], dr[8]);
}