如何检查datagridview中是否已存在Items

时间:2017-07-29 07:10:34

标签: c# datagridview

如果新的输入条形码已经存在于datagridview中,并且如果存在,则添加数量或总和。

3 个答案:

答案 0 :(得分:1)

将条形码列设置为datakey,并在需要添加新行时使用Datagrid.Rows.Find([条形码值])搜索该值是否存在

答案 1 :(得分:1)

尝试此测试代码调用dataGridview_CellEndEdit事件:

    private void GvOpStock_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        try
        {
            if (e.ColumnIndex != 0) 

                for (int row = 0; row < GvOpStock.Rows.Count - 1; row++)
                {

                    if (GvOpStock.Rows[row].Cells[1].Value != null &&
                        row != e.RowIndex &&
                        GvOpStock.Rows[row].Cells[1].Value.Equals(GvOpStock.Rows[e.RowIndex].Cells[e.ColumnIndex].Value))
                    {

                        MessageBox.Show("Duplicate");
                        return;

                    }
                    else
                    {

                        //Add To datagridview

                    }

                }
        }
        catch (Exception ex)
        {

        }
    }

答案 2 :(得分:0)

我得到了一个问题的答案

Boolean found = false;

        if (!string.IsNullOrWhiteSpace(this.textBox1.Text))
        {

            if (e.KeyCode == Keys.Enter)
            {
                string conbarcode = this.textBox1.Text;

                conbarcode = this.textBox1.TextLength == 10 ? this.textBox1.Text : Convert.ToDouble(this.textBox1.Text).ToString("0000000000").ToString();

                foreach (DataGridViewRow row in this.dataGridView1.Rows)
                {
                    if (row.Cells[0].Value.Equals(conbarcode))
                    {
                        // row exists
                        found = true;

                        row.Cells["qty"].Value = Convert.ToInt32(row.Cells["qty"].Value) + 1;
                        row.Cells["qty"].Selected = true;
                        //MessageBox.Show("Row already exists");
                        break;
                    }
                }

                if (found)
                {
                    this.textBox1.BackColor = Color.LightGreen;
                    return;
                }