Reputation: 3
I want unique rows. The loop should check all rows in the datagridview and see if it matches with the text from textbox, if not, it will add the value from the textbox to the datagridview. My problem: only the first row works, the loop only iterate through the first row in the datagridview, why wont it continue through the other rows?
private void laggtill_Click(object sender, EventArgs e)
{
bool dublett = false;
foreach (DataGridViewRow r in dataGridView1.Rows)
{
if(r.Cells[0].Value.ToString() == txtNamn.Text) // txtnamn is a textbox
{
dublett = true;
MessageBox.Show("Varan finns redan, gör om!");
}
break;
}
if(dublett == false)
{
DataRow dr;
dr = dt.NewRow();
dr["Namn"] = txtNamn.Text;
dr["Pris"] = txtPris.Text;
dr["Varunummer"] = txtVNr.Text;
dr["Saldo"] = txtSaldo.Text;
dt.Rows.Add(dr);
dataGridView1.DataSource = dt.DefaultView;
clearRow();
spara();
}
txtNamn.Text = "";
txtPris.Text = "";
txtSaldo.Text = "";
txtVNr.Text = "";
}
Upvotes: 0
Views: 1291
Reputation: 576
if(r.Cells[0].Value.ToString() == txtNamn.Text) // txtnamn is a textbox
{
dublett = true;
MessageBox.Show("Varan finns redan, gör om!");
break;
}
Move the break; inside the if.
Upvotes: 1