在DataGridView的现有项目中添加数量的问题-vb.net

穆图·库马尔

我正在创建一个购物系统,作为我的大学迷你项目,用户可以在其中输入他们想要的商品的条形码,输入的商品将被添加到右侧的网格中,并且作为新的商品添加到左侧的网格中。每个项目都有唯一的条形码,并且可以具有相同的产品代码。当用户输入具有相同产品代码的商品时,数量将添加到左侧的网格中。我遇到一个问题,当需要添加第二个项目数量时,系统会将其检测为新项目,而不是添加数量

例如:产品和物品示例

    Public Sub addRecordTo2ndDGV()
    Try
        dbconnection()
        sql = "SELECT * FROM items_database WHERE Item_Barcode = @ItemBarcode;"
        cmd = New MySqlCommand
        With cmd
            .Connection = conn
            .CommandText = sql
            .Parameters.Clear()
            .Parameters.AddWithValue("@ItemBarcode", formUser.barcodeTB.Text)
        End With
        da = New MySqlDataAdapter
        dt = New DataTable
        da.SelectCommand = cmd
        da.Fill(dt)
        If dt.Rows.Count > 0 Then
            Dim ItemProductCode, ItemBarcode As String
            Dim repeated As Boolean = False
            ItemProductCode = dt.Rows(0).Item(1)
            ItemBarcode = dt.Rows(0).Item(2)
            formUser.itemproductcodeTB.Text = ItemProductCode
            formUser.itembarcodetb.Text = ItemBarcode
            
            For Each row2 As DataGridViewRow In formUser.ItemBarcodeDGV.Rows
                If Convert.ToString(row2.Cells(1).Value) = formUser.itembarcodetb.Text AndAlso Convert.ToString(row2.Cells(0).Value) = formUser.itemproductcodeTB.Text Then
                    MsgBox("QUANTITY WILL MINUS")
                    minusQuantity()
                    formUser.ItemBarcodeDGV.Rows.Remove(row2)
                    MsgBox("QUANTITY HAS MINUS")
                    Exit For

                ElseIf Convert.ToString(row2.Cells(1).Value) <> formUser.itembarcodetb.Text AndAlso Convert.ToString(row2.Cells(0).Value) = formUser.itemproductcodeTB.Text Then
                    MsgBox("QUANTITY WILL ADD")
                    formUser.ItemBarcodeDGV.Rows.Add(New String() {formUser.itemproductcodeTB.Text, formUser.itembarcodetb.Text})
                    addQuantity()
                    MsgBox("QUANTITY HAS ADDED")
                    Exit For

                ElseIf Convert.ToString(row2.Cells(1).Value) <> formUser.itembarcodetb.Text AndAlso Convert.ToString(row2.Cells(0).Value) <> formUser.itemproductcodeTB.Text Then
                    MsgBox("NEW ITEM")
                    formUser.ItemBarcodeDGV.Rows.Add(New String() {formUser.itemproductcodeTB.Text, formUser.itembarcodetb.Text})
                    addRecord()
                    MsgBox("REGISTERED SUCCESSFULL")
                    Exit For
                End If
                Exit For
            Next
        Else
            MsgBox("Barcode not registered!")
            formUser.barcodeTB.Text = ""
            formUser.barcodeTB.Focus()
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    Finally
        conn.Close()
        da.Dispose()
        formUser.barcodeTB.Text = ""
        clearUserForm()
        retrieveSubTotal()
    End Try
End Sub

Public Sub addRecord()
    If formUser.itemproductcodeTB.Text = "" Then
        MsgBox("Scan a barcode")
    Else
        Try
            dbconnection()
            sql = "SELECT * FROM products_database WHERE Product_Code = @ProductCode;"
            cmd = New MySqlCommand
            With cmd
                .Connection = conn
                .CommandText = sql
                .Parameters.Clear()
                .Parameters.AddWithValue("@ProductCode", formUser.itemproductcodeTB.Text)
            End With
            da = New MySqlDataAdapter
            dt = New DataTable
            da.SelectCommand = cmd
            da.Fill(dt)
            If dt.Rows.Count > 0 Then
                Dim productcode, itemdescription, unitprice As String
                Dim repeated As Boolean = False
                productcode = dt.Rows(0).Item(1)
                itemdescription = dt.Rows(0).Item(3)
                unitprice = dt.Rows(0).Item(4)
                formUser.productcodeTB.Text = productcode
                formUser.itemdescriptionTB.Text = itemdescription
                formUser.unitpriceTB.Text = unitprice
                formUser.unitQuantityTB.Text = "1"

                For Each row As DataGridViewRow In formUser.ProductAddToCartDGV.Rows
                    If Convert.ToString(row.Cells(0).Value) = formUser.productcodeTB.Text AndAlso Convert.ToString(row.Cells(2).Value) = formUser.unitpriceTB.Text Then
                        row.Cells(4).Value = Convert.ToString(row.Cells(3).Value * row.Cells(2).Value)
                    End If
                Next
                formUser.ProductAddToCartDGV.Rows.Add(New String() {formUser.productcodeTB.Text, formUser.itemdescriptionTB.Text, formUser.unitpriceTB.Text, formUser.unitQuantityTB.Text, formUser.unitpriceTB.Text})
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            conn.Close()
            da.Dispose()
        End Try
    End If
End Sub

Public Sub addQuantity()
    If formUser.itemproductcodeTB.Text = "" Then
        MsgBox("Scan a barcode")
    Else
        Try
            dbconnection()
            sql = "SELECT * FROM products_database WHERE Product_Code = @ProductCode;"
            cmd = New MySqlCommand
            With cmd
                .Connection = conn
                .CommandText = sql
                .Parameters.Clear()
                .Parameters.AddWithValue("@ProductCode", formUser.itemproductcodeTB.Text)
            End With
            da = New MySqlDataAdapter
            dt = New DataTable
            da.SelectCommand = cmd
            da.Fill(dt)
            If dt.Rows.Count > 0 Then
                Dim productcode, itemdescription, unitprice As String
                Dim repeated As Boolean = False
                productcode = dt.Rows(0).Item(1)
                itemdescription = dt.Rows(0).Item(3)
                unitprice = dt.Rows(0).Item(4)

                formUser.productcodeTB.Text = productcode
                formUser.itemdescriptionTB.Text = itemdescription
                formUser.unitpriceTB.Text = unitprice
                formUser.unitQuantityTB.Text = "1"

                For Each row As DataGridViewRow In formUser.ProductAddToCartDGV.Rows
                    If Convert.ToString(row.Cells(0).Value) = formUser.productcodeTB.Text AndAlso Convert.ToString(row.Cells(2).Value) = formUser.unitpriceTB.Text Then
                        row.Cells(3).Value = Convert.ToString(Convert.ToInt16(row.Cells(3).Value + 1))
                        row.Cells(4).Value = Convert.ToString(row.Cells(3).Value * row.Cells(2).Value)
                    End If
                Next
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            conn.Close()
            da.Dispose()
        End Try
    End If
End Sub

Public Sub minusQuantity()
    If formUser.itemproductcodeTB.Text = "" Then
        MsgBox("Scan a barcode")
    Else
        Try
            dbconnection()
            sql = "SELECT * FROM products_database WHERE Product_Code = @ProductCode;"
            cmd = New MySqlCommand
            With cmd
                .Connection = conn
                .CommandText = sql
                .Parameters.Clear()
                .Parameters.AddWithValue("@ProductCode", formUser.itemproductcodeTB.Text)
            End With
            da = New MySqlDataAdapter
            dt = New DataTable
            da.SelectCommand = cmd
            da.Fill(dt)
            If dt.Rows.Count > 0 Then
                Dim productcode, itemdescription, unitprice As String
                Dim repeated As Boolean = False
                productcode = dt.Rows(0).Item(1)
                itemdescription = dt.Rows(0).Item(3)
                unitprice = dt.Rows(0).Item(4)

                formUser.productcodeTB.Text = productcode
                formUser.itemdescriptionTB.Text = itemdescription
                formUser.unitpriceTB.Text = unitprice
                formUser.unitQuantityTB.Text = "1"

                For Each row As DataGridViewRow In formUser.ProductAddToCartDGV.Rows
                    If Convert.ToString(row.Cells(0).Value) = formUser.productcodeTB.Text AndAlso Convert.ToString(row.Cells(2).Value) = formUser.unitpriceTB.Text Then
                        row.Cells(3).Value = Convert.ToString(Convert.ToInt16(row.Cells(3).Value - 1))
                        row.Cells(4).Value = Convert.ToString(row.Cells(3).Value * row.Cells(2).Value)
                    End If
                Next
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            conn.Close()
            da.Dispose()
        End Try
    End If
End Sub

这是输出图像

凯斯·贾德

这是我的处理方式:

  • 制作一个新项目
  • 将Form1重命名为MainForm
  • 添加一个数据集类型的文件,称为ProdDataSet。关闭它VS打开它
  • 在文本编辑器中打开ProdDataSet.xsd并将其粘贴到整个内容的顶部:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="ProdDataSet" targetNamespace="http://tempuri.org/ProdDataSet.xsd" xmlns:mstns="http://tempuri.org/ProdDataSet.xsd" xmlns="http://tempuri.org/ProdDataSet.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:msprop="urn:schemas-microsoft-com:xml-msprop" attributeFormDefault="qualified" elementFormDefault="qualified">
  <xs:annotation>
    <xs:appinfo source="urn:schemas-microsoft-com:xml-msdatasource">
      <DataSource DefaultConnectionIndex="0" FunctionsComponentName="QueriesTableAdapter" Modifier="AutoLayout, AnsiClass, Class, Public" SchemaSerializationMode="IncludeSchema" xmlns="urn:schemas-microsoft-com:xml-msdatasource">
        <Connections />
        <Tables />
        <Sources />
      </DataSource>
    </xs:appinfo>
  </xs:annotation>
  <xs:element name="ProdDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true" msprop:EnableTableAdapterManager="true" msprop:Generator_DataSetName="ProdDataSet" msprop:Generator_UserDSName="ProdDataSet">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="Products" msprop:Generator_TableClassName="ProductsDataTable" msprop:Generator_TableVarName="tableProducts" msprop:Generator_TablePropName="Products" msprop:Generator_RowDeletingName="ProductsRowDeleting" msprop:Generator_RowChangingName="ProductsRowChanging" msprop:Generator_RowEvHandlerName="ProductsRowChangeEventHandler" msprop:Generator_RowDeletedName="ProductsRowDeleted" msprop:Generator_UserTableName="Products" msprop:Generator_RowChangedName="ProductsRowChanged" msprop:Generator_RowEvArgName="ProductsRowChangeEvent" msprop:Generator_RowClassName="ProductsRow">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="Id" msprop:Generator_ColumnVarNameInTable="columnId" msprop:Generator_ColumnPropNameInRow="Id" msprop:Generator_ColumnPropNameInTable="IdColumn" msprop:Generator_UserColumnName="Id" type="xs:int" />
              <xs:element name="Name" msprop:Generator_ColumnVarNameInTable="columnName" msprop:Generator_ColumnPropNameInRow="Name" msprop:Generator_ColumnPropNameInTable="NameColumn" msprop:Generator_UserColumnName="Name" type="xs:string" minOccurs="0" />
              <xs:element name="Price" msprop:Generator_ColumnVarNameInTable="columnPrice" msprop:Generator_ColumnPropNameInRow="Price" msprop:Generator_ColumnPropNameInTable="PriceColumn" msprop:Generator_UserColumnName="Price" type="xs:double" minOccurs="0" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        <xs:element name="Order" msprop:Generator_TableClassName="OrderDataTable" msprop:Generator_TableVarName="tableOrder" msprop:Generator_TablePropName="Order" msprop:Generator_RowDeletingName="OrderRowDeleting" msprop:Generator_RowChangingName="OrderRowChanging" msprop:Generator_RowEvHandlerName="OrderRowChangeEventHandler" msprop:Generator_RowDeletedName="OrderRowDeleted" msprop:Generator_UserTableName="Order" msprop:Generator_RowChangedName="OrderRowChanged" msprop:Generator_RowEvArgName="OrderRowChangeEvent" msprop:Generator_RowClassName="OrderRow">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="ProductId" msprop:Generator_ColumnVarNameInTable="columnProductId" msprop:Generator_ColumnPropNameInRow="ProductId" msprop:Generator_ColumnPropNameInTable="ProductIdColumn" msprop:Generator_UserColumnName="ProductId" type="xs:int" />
              <xs:element name="Qty" msprop:Generator_ColumnVarNameInTable="columnQty" msprop:Generator_ColumnPropNameInRow="Qty" msprop:Generator_ColumnPropNameInTable="QtyColumn" msprop:Generator_UserColumnName="Qty" type="xs:int" minOccurs="0" />
              <xs:element name="UnitPrice" msprop:Generator_ColumnVarNameInTable="columnUnitPrice" msprop:Generator_ColumnPropNameInRow="UnitPrice" msprop:Generator_ColumnPropNameInTable="UnitPriceColumn" msprop:Generator_UserColumnName="UnitPrice" type="xs:double" minOccurs="0" />
              <xs:element name="Total" msdata:ReadOnly="true" msdata:Expression="[Qty]*[UnitPrice]" msprop:Generator_ColumnVarNameInTable="columnTotal" msprop:Generator_ColumnPropNameInRow="Total" msprop:Generator_ColumnPropNameInTable="TotalColumn" msprop:Generator_UserColumnName="Total" type="xs:double" minOccurs="0" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
    <xs:unique name="Constraint1" msdata:PrimaryKey="true">
      <xs:selector xpath=".//mstns:Products" />
      <xs:field xpath="mstns:Id" />
    </xs:unique>
    <xs:unique name="Order_Constraint1" msdata:ConstraintName="Constraint1" msdata:PrimaryKey="true">
      <xs:selector xpath=".//mstns:Order" />
      <xs:field xpath="mstns:ProductId" />
    </xs:unique>
  </xs:element>
</xs:schema>
  • 保存。在Visual Studio的设计器视图中重新打开它(双击它)并将表排列在一点内,然后再次保存(将它保存在设计器中时会生成必要的代码)
  • 将NumericUpDown控件添加到窗体,并将其命名为_prodIdNumericUpDown
  • 将一个按钮添加到窗体,称为_addButton。双击它并将此代码放入处理程序中:

        Dim prod = _prodDataSet.Products.FindById(CInt(_prodIdNumericUpDown.Value))

        If prod Is Nothing Then
            MessageBox.Show("Not a product id")
            Return
        End If


        'lookup the product in the order
        Dim orderedProduct = _prodDataSet.Order.FindByProductId(prod.Id)

        If orderedProduct Is Nothing Then
            _prodDataSet.Order.AddOrderRow(prod.Id, 1, prod.Price)
        Else
            orderedProduct.Qty += 1
        End If
  • 将此代码放在表单的构造函数中:

        'put it after InitializeComponent()
        _prodDataSet.Products.AddProductsRow(1, "apples", 1.23)
        _prodDataSet.Products.AddProductsRow(2, "oranges", 2.34)
        _prodDataSet.Products.AddProductsRow(3, "pears", 3.45)
    
  • 打开数据源窗口(“查看”菜单,其他窗口)并将每个“订单”和“产品”节点拖到表单上以创建网格。在表单底部的托盘中,确保将数据集重命名为_prodDataSet
  • 运行程序

看起来像这样。选择一种产品,单击添加,第一次单击它会将产品添加到订单中。第二次单击它会增加现有项目的数量-如果您使用数据集/数据表,则大约需要5行代码(恕我直言,这是应该这样做的一种方式):

在此处输入图片说明

现在,您要做的就是挂接所有东西,以便将数据库数据输入到数据表中,而不是数据网格中。这很容易-在设计器中打开该DataSet,右键单击表面并选择Add TableAdapter。通过向导将数据集连接到您的mysql数据库。(您需要安装用于Visual Studio的MySQL才能使生活变得轻松)

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章