我需要一个解决方案。我想从一个表中减去/添加一个字段值与另一个表。我提供了详细信息。
我有两张桌子(相同的结构)。
表1 - purchase
字段:id, purchase_from, product_name, quantity, rate
表2 - sales
字段:id, sale_to, product_name, quantity, rate
现在我想将数量从purchase
表减去sales
表,并将数据显示到数据网格视图中。
我试过了,但失败了。我已经为您提供了代码段。
Dim PurchasePrdName, SalesPrdName As String
Dim PurchaseQty, SalesQty As Double
Private Sub LoadPurchase()
Try
OpenConnection()
Dim dcommand As New MySqlCommand
Dim qry As String = "SELECT ProductName,SUM(Quantity) FROM stockitems GROUP BY ProductId"
dcommand.Connection = conn
dcommand.CommandText = qry
Dim dbread As MySqlDataReader = dcommand.ExecuteReader
DataGridView1.Rows.Clear()
While dbread.Read
If dbread.HasRows Then
PurchasePrdName = dbread("ProductName").ToString
PurchaseQty = dbread("SUM(Quantity)").ToString
End If
End While
dbread.Close()
Catch ex As Exception
MsgBox(ex.Message)
Finally
CloseConnection()
End Try
End Sub
Private Sub LoadSales()
Try
OpenConnection()
Dim dcommand As New MySqlCommand
Dim qry As String = "SELECT SUM(Quantity) FROM salesitems WHERE ProductName='" & PurchasePrdName & "' GROUP BY ProductId"
dcommand.Connection = conn
dcommand.CommandText = qry
Dim dbread As MySqlDataReader = dcommand.ExecuteReader
DataGridView1.Rows.Clear()
While dbread.Read
If dbread.HasRows Then
SalesQty = dbread("SUM(Quantity)").ToString
End If
End While
dbread.Close()
Catch ex As Exception
MsgBox(ex.Message)
Finally
CloseConnection()
End Try
End Sub
然后将此数据加载到DataGridView ...
Private Sub LoadData()
Try
LoadPurchase()
LoadSales()
Dim PrdName As String = PurchasePrdName
Dim Qty As Double = PurchaseQty - SalesQty
DataGridView1.Rows.Add(PrdName, Qty)
DbGridCustomize()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
但它只显示表中的一个产品。我混淆了为什么!!!
你能帮我解决这个问题吗?
我非常感谢你
答案 0 :(得分:5)
您只向网格添加一行,这是分配给PurchasePrdName的产品。您需要将一组值绑定到网格,或者需要迭代一组值。看起来好像你在这里所做的就是为变量分配一个值,然后在网格中添加一行:
DataGridView1.Rows.Add(PrdName, Qty)
编辑:
我会将您的变量PurchasePrdName和SalePrdName更改为集合,因为您希望在此处存储多个值。
Private PurchasePrdName As Dictionary(Of String, Double)
Private SalesPrdName As Dictionary(Of String, Double)
然后当你加载购买和销售时,你会做这样的事情:
While dbread.Read
If dbread.HasRows Then
PurchasePrdName.Add(dbread("ProductName").ToString, dbread("SUM(Quantity)"))
End If
End While
然后,当您进行销售时,您需要遍历产品词典以提取每个产品名称。您可以存储销售数量,但您也可以同时计算差额并存储。最好创建一个包含所有项目的类,并将它们存储在一个字典中。
在销售负载中,您将迭代字典
For Each product In PurchasePrdName.Keys
Dim qry As String = "SELECT SUM(Quantity) FROM salesitems WHERE ProductName='" & product & "' GROUP BY ProductId"
dcommand.CommandText = qry
Dim dbread As MySqlDataReader = dcommand.ExecuteReader
DataGridView1.Rows.Clear()
While dbread.Read
If dbread.HasRows Then
SalesPrdName.Add(product, PurchasePrdName(product) - Double.Parse(dbread("SUM(Quantity)")))
End If
End While
dbread.Close()
Next
最后你还想在循环中添加行......
For Each product In SalesPrdName.Keys
DataGridView1.Rows.Add(product, SalesPrdName(product))
Next
您可能希望更改变量名称以反映其新含义等。如果您想存储销售数量,那么我建议您使用一个字典,其中产品名称为键,类为值。该课程将包括产品名称,产品数量,销售数量以及两者之间的差异。