我得到了这个代码,它从datagridview1中选择不同的值并将结果传递给datagridview2:
进一步详情: 来自datagridview1的数据
Code Amount
Pro1 100.00
Pro2 300.00
Pro1 100.00
Pro1 100.00
Pro2 300.00
结果应该放在datagridview2中,如下所示;
Code Amount Count
Pro1 100.00 3
Pro2 300.00 2
CODE:
Dim dic As New Dictionary(Of String, Integer)()
Dim cellValue As String = Nothing
For i As Integer = 0 To dgvSubjectsEnrolled.Rows.Count - 1
If Not dgvSubjectsEnrolled.Rows(i).IsNewRow Then
If dgvSubjectsEnrolled(0, i).Value > 0 Then
cellValue = dgvSubjectsEnrolled(0, i).Value.ToString()
If Not dic.ContainsKey(cellValue) Then
dic.Add(cellValue, 1)
Else
dic(cellValue) += 1
End If
Else
End If
End If
Next
Dim sb1 As New StringBuilder()
Dim sb2 As New StringBuilder()
For Each keyvalue As KeyValuePair(Of String, Integer) In dic
sb1.AppendLine(String.Format("{0}", keyvalue.Key, keyvalue.Value))
sb2.AppendLine(String.Format("{1}", keyvalue.Key, keyvalue.Value))
Next
Me.dgvsub.Rows.Add(sb1.ToString, sb2.ToString())
代码执行成功但结果是:
Code Count
Pro1Pro2 32
数据与同一行连接在一起。下一个值应该在下一行。 请编辑此代码。
答案 0 :(得分:0)
一种方法,使用字典而不是列表:
Private Sub copyDGVs()
Dim values As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)()
Dim i As Integer = 1
Dim tmp As String
Dim arr As String()
'Make a list of distinct values from DataGridView1, track the count.
For Each row As DataGridViewRow In dgv1.Rows
tmp = ""
For j As Integer = 0 To row.Cells.Count - 1
tmp &= row.Cells(j).Value & "-"
Next
If (Not values.ContainsKey(tmp)) Then
values.Add(tmp, 1)
Else
values(tmp) += 1
End If
Next
'Copy that list into DataGridView2
For Each guy As KeyValuePair(Of String, Integer) In values
arr = guy.Key.Split("-")
For q As Integer = 0 To arr.Length - 1
dgv2.Rows(i).Cells(q + 1).Value = arr(q)
If (q = arr.Length - 1) Then
dgv2.Rows(i).Cells(q + 2).Value = guy.Value
End If
Next
i += 1
Next
End Sub
这不是我写过的美貌,但它应该做你需要的东西,除非我对索引进行了嘲笑。
PER COMMENTS / EDIT:
我认为现在的问题是你要附加到你的stringbuilders,从不重置它们,也不要写入循环内部。尝试这样的事情,看看它是否更好:
Dim sb1 As StringBuilder()
Dim sb2 As StringBuilder()
For Each keyvalue As KeyValuePair(Of String, Integer) In dic
sb1 = New StringBuilder()
sb2 = New StringBuilder()
sb1.AppendLine(String.Format("{0}", keyvalue.Key, keyvalue.Value))
sb2.AppendLine(String.Format("{1}", keyvalue.Key, keyvalue.Value))
Me.dgvsub.Rows.Add(sb1.ToString, sb2.ToString())
Next