我正在尝试将值相加Datagridview1(Table1)
并将其保存到Datagridview2(Table2)
两者DGVs
都是Databound
并且都具有相同的 2 列Name, Quantity
。
我Childform1(DGV1)
有一个Textbox1
和一个Post
按钮。
用户必须输入一个Name
onTextbox1
并点击Post
,然后所有与输入的on相同的Quantity
onDGV1
必须相加。Name
Textbox1
前任:
表格1
Name | Quantity
a 10
b 5
a 10
b 5
按下POST
按钮后
表 2
Name | Quantity
a 20
b 10
代码
Dim occurences As New Dictionary(Of String, Double)
Dim oTempObjects As New List(Of DataGridViewRow)
MasterForm.oTransferRows = oTempObjects
For Each xRow As DataGridViewRow In Datagridview1.Rows
If (Not xRow.Cells("GVName").Value Is Nothing AndAlso xRow.Cells("GVName").Value.ToString() = TextBox1.Text) Then
oTempObjects.Add(xRow)
End If
Next
Dim _Name As New List(Of String)
For Each xRows In MasterForm.oTransferRows
_Name.Add("'" & xRows.Cells("GVName").Value.ToString() & "'")
Dim inClause1 As String = String.Join(",", _Name.ToArray())
Dim _sqlUpdate As String = String.Format("UPDATE tested SET Posted = @Posted WHERE Name IN ({0})", inClause1)
Using _conn As New MySqlConnection("Server = localhost; Username= root; Password =; Database = test")
Using _commm As New MySqlCommand()
With _commm
.CommandText = _sqlUpdate
.Connection = _conn
.CommandType = CommandType.Text
.Parameters.AddWithValue("@Posted", "Yes")
End With
Try
_conn.Open()
_commm.ExecuteNonQuery()
Catch ex As MySqlException
MsgBox(ex.StackTrace.ToString)
End Try
_conn.Close()
End Using
End Using
If (occurences.ContainsKey(xRows.Cells(1).Value.ToString())) Then
occurences(xRows.Cells(1).Value.ToString()) = Double.Parse(occurences(xRows.Cells(1).Value.ToString()).ToString()) + Double.Parse(xRows.Cells(4).Value.ToString())
Else
occurences.Add(xRows.Cells(1).Value.ToString(), Double.Parse(xRows.Cells(4).Value.ToString()))
End If
Next
For Each KVP As KeyValuePair(Of String, Double) In occurences
oChildForm2.DataGridView2.Rows.Add(New Object() {KVP.Key, KVP.Value})
Next
Dim xlist As List(Of KeyValuePair(Of String, Double)) = occurences.ToList
For Each pair As KeyValuePair(Of String, Double) In occurences
Dim oUpdateString = String.Format("Insert Into testing (Name, Quantity) VALUES (@iName, @iQty)")
Using _conn As New MySqlConnection("Server = localhost; Username= root; Password =; Database = test")
Using _commm As New MySqlCommand()
With _commm
.CommandText = oUpdateString
.Connection = _conn
.CommandType = CommandType.Text
.Parameters.AddWithValue("@iName", pair.Key)
.Parameters.AddWithValue("@iQty", pair.Value)
End With
Try
_conn.Open()
_commm.ExecuteNonQuery()
Catch ex As MySqlException
MsgBox(ex.StackTrace.ToString)
End Try
_conn.Close()
End Using
End Using
Next
此代码仅DGV1
在第一次单击时汇总相同的名称并将其保存在DGV2
.
但例如我添加了另一个DGV1
同名的数据,
我希望将新添加数据的 QUANTITY 添加到 DGV2 上现有数据的当前总和中。
对此也有一点帮助会非常棒。**
前任:
表 2
Name | Quantity
a 20
b 10
然后我在表 1 中添加数据
表格1
Name | Quantity
a 20
b 10
发帖后
表2
Name | Quantity
a 40
b 20