如果产品存在于DataGridView中,则添加数量

时间:2019-01-04 08:06:10

标签: vb.net

有人可以帮助我解决我的问题吗?

下图显示了我输入的相同项目。我想要的是我不希望在DataGridView中显示重复项。如果添加了相同的产品记录,则不会显示新的记录,它只是在单击“保存”按钮时添加数量。而且我不知道如何编码,我只是vb.net的新手。有人可以帮我怎么做吗?如果这样做的话,对我来说将是很大的帮助,非常感谢!

pic1

以下是我的“保存”按钮的代码:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        initializeCon()

    Dim found As Boolean = False

    If (DataGridView1.Rows.Count > 0) Then
        For Each row As DataGridViewRow In DataGridView1.Rows
            If (Convert.ToString(row.Cells(1).Value) = dtDate.Text) And (Convert.ToString(row.Cells(2).Value) = txtProductCode.Text) AndAlso
            (Convert.ToString(row.Cells(3).Value) = txtProductName.Text) Then
                row.Cells(4).Value = Convert.ToString(txtQuantity.Text + Convert.ToInt16(row.Cells(4).Value))
                found = True
            End If
        Next
        If Not found Then
            cmd = New SqlCommand("INSERT INTO tbl_productOrders VALUES('" & txtID.Text & "','" & dtDate.Text & "','" & txtProductCode.Text & "','" & txtProductName.Text & "'," & txtQuantity.Text & ");", con)
            cmd.ExecuteNonQuery()
            clrtxt()
            SaveMsg()
            Getdata()
        End If
    End If
End Sub

2 个答案:

答案 0 :(得分:0)

这是一个避免在添加行时重复的举动

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim exist As Boolean = False, numrow As Integer = 0, numtext As Integer 
    For Each itm As DataGridViewRow In DataGridView1.Rows
        If itm.Cells(0).Value IsNot Nothing Then
            If itm.Cells(0).Value.ToString = TextBox1.Text Then
                exist = True
                numrow = itm.Index
                numtext = CInt(itm.Cells(1).Value)
                Exit For
            End If
        End If
    Next
    If exist = False Then
        DataGridView1.Rows.Add(New String() {TextBox1.Text, TextBox2.Text})
    Else
        DataGridView1.Rows(numrow).Cells(1).Value = CInt(TextBox2.Text) + numtext
    End If
End Sub

答案 1 :(得分:0)

有两个方面可以改善您的程序。

1。使产品比较更好

由于需要检查单个属性以找到相等的乘积,因此更好的方法是重载==运算符以及实现IEquatable接口。您可以阅读更多here。执行此操作时,可以将产品与==运算符:if (product1 == product2) { }进行比较。在这种情况下,将比较三个属性。如果它们都相同,则两个乘积相等。

2。使添加产品到DataGridView更容易

为了使向DataGridView添加产品更加容易,您需要利用Windows窗体中便捷的绑定机制,该机制出现在.NET Framework 2.0-BindingSource中。它就像您的数据和控件之间的媒介。为了使此类可用,您需要使用另一个方便的类-BindingList。您将BindingList馈送到BindingSource并将BindingSource分配给DataGridView的DataSource属性。之后,您只能使用BindingList集合(添加/删除/编辑)-所有传播都由BindinSource完成。

总结,这是说明和完整代码。 Here您可以下载项目本身。

  1. 添加产品时,代码首先检查DataGridView中是否已存在此类产品(Add product按钮)。请注意,我们不直接与DataGridView一起使用-我们仅对集合使用 。多亏了增强功能,我们可以在这里使用LINQ。如果找不到产品,我们将其添加到集合中。如果找到,我们将更新数量。

  2. 如果您需要更新选定的产品数据(Change quantity按钮),则只需从选定的行中检索它并使用BoundDataItem-这就是我们的产品所在的位置。然后只需更新所需产品的属性即可。

  3. 如果您要删除产品(Delete product按钮),请从选定的行中检索它,并将其从集合中删除。

重要!在完成所有操作后,请不要忘记在DataGridView上调用Refresh()方法以查看更改。

IMG1

namespace WinFormsApp
{
    public partial class Root : Form
    {

        private BindingList<Product> list = null;
        private BindingSource bindingSource = null;

        public Root() => InitializeComponent();

        private void OnFormLoaded(object sender, EventArgs e)
        {
            // Our collection holding products
            list = new BindingList<Product>();
            // I've set up columns manually (with applied binding),
            // so switch generating columns off.
            dataGrid.AutoGenerateColumns = false;
            // Disable adding new row
            dataGrid.AllowUserToAddRows = false;
            // Create our medium between grid and collection
            bindingSource = new BindingSource { DataSource = list };
            // Set binding
            dataGrid.DataSource = bindingSource;
        }

        private void OnAddRecord(object sender, EventArgs e)
        {
            // Create new product
            var new_product = new Product
            {
                Date = dtPicker.Value.ToShortDateString(),
                Code = txtCode.Text,
                Name = txtName.Text,
                Quantity = npQuantity.Value
            };
            // No need to check individual properties here
            // as == and IEquatable will do all the work.
            // We can safely use LINQ here.
            var p = list.FirstOrDefault(x => x == new_product);
            if (p == null)
            {
                // Product is not found. Add it to list.
                list.Add(new_product);
            }
            else
            {
                // Product is found. Update quantity.
                p.Quantity += new_product.Quantity;
            }
            dataGrid.Refresh(); //Required to reflect changes
        }

        private void OnChangeQuantity(object sender, EventArgs e)
        {
            // Change quantity here.
            var product = GetProduct();
            if (product != null)
            {
                // Update product's quantity.
                product.Quantity *= 2;
                // Do not forget to refresh grid.
                dataGrid.Refresh();
            }
        }

        private void OnDeleteProduct(object sender, EventArgs e)
        {
            // Delete product here.
            var product = GetProduct();
            if (product != null)
            {
                // We need to delete product only from collection
                list.Remove(product);
                // Do not forget to refresh grid
                dataGrid.Refresh();
            }
        }

        // Retrieve product from selected row.
        private Product GetProduct() =>
            dataGrid.SelectedCells.Count == 0 ?
                null :
                dataGrid.SelectedCells[0].OwningRow.DataBoundItem as Product;
    }

    class Product : IEquatable<Product>
    {
        public string Date { get; set; }
        public string Code { get; set; }
        public string Name { get; set; }
        public decimal Quantity { get; set; }

        // Overload == operator
        public static bool operator ==(Product firstProduct, Product secondProduct)
        {
            // Check for null on left side.
            if (Object.ReferenceEquals(firstProduct, null))
            {
                if (Object.ReferenceEquals(secondProduct, null))
                {
                    // null == null = true.
                    return true;
                }
                // Only the left side is null.
                return false;
            }
            // Equals handles case of null on right side.
            return firstProduct.Equals(secondProduct);
        }

        // Overload != operator (required when overloading == operator)
        public static bool operator !=(Product firstProduct, Product secondProduct) =>
              !(firstProduct == secondProduct);

        // Implementing IEquatable<T> interface
        public bool Equals(Product other)
        {
            // If 'other' is null, return false.
            if (Object.ReferenceEquals(other, null))
            {
                return false;
            }

            // Optimization for a common success case.
            if (Object.ReferenceEquals(this, other))
            {
                return true;
            }

            // If run-time types are not exactly the same, return false.
            if (this.GetType() != other.GetType())
            {
                return false;
            }

            // Return true if the fields match.
            return
                Date == other.Date &&
                Code == other.Code &&
                Name == other.Name;
        }

        public override bool Equals(object obj) => this.Equals(obj as Product);

        public override int GetHashCode() =>
            Date.GetHashCode() + Code.GetHashCode() + Name.GetHashCode();

        // Optional. For debugging purposes.
        public override string ToString() =>
            $"Date: {Date}, Code: {Code}, Name: {Name}, Quantity: {Quantity}";
    }
}