简体   繁体   English

从datagridview c#中删除重复的行

[英]Remove duplicated row from datagridview c#

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. 该循环应检查datagridview中的所有行,并查看其是否与文本框中的文本匹配,如果不匹配,它将把文本框中的值添加到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? 我的问题:仅第一行有效,循环仅遍历datagridview中的第一行,为什么不继续遍历其他行?

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 = "";            
        }
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. 如果里面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM