从datagridview1中选择Distinct values并传递给vb.net中的datagridview2

时间:2017-11-05 03:57:40

标签: vb.net

如何从datagridview1中选择不同的值并将此值传递给datagridview2?

我上传了这张图片,你介意看看我的问题的更多细节;

Scenario

我已经尝试过这段代码,但似乎没有用;

Private Sub GetLabandOtherFees()
        Dim DistinctValues() As String = (From row As DataGridViewRow In dgvSubjectsEnrolled.Rows.Cast(Of DataGridViewRow)() _
                                            Where Not row.IsNewRow _
                                            Select CStr(row.Cells(0).Value)).Distinct.ToArray

        For Each row As DataGridViewRow In dgvsub.Rows
            dgvsub.Rows(row.Index).Cells(0).Value = DistinctValues
        Next
    End Sub

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

试试这个。

Private Sub GetLabandOtherFees()
        Dim dic As New Dictionary(Of String, Integer)()
        Dim cellValue As String = Nothing
        For i As Integer = 0 To datagridview1.Rows.Count - 1
            If Not datagridview1.Rows(i).IsNewRow Then
                cellValue = datagridview1(0, i).Value.ToString()
                If Not dic.ContainsKey(cellValue) Then
                    dic.Add(cellValue, 1)
                Else
                    dic(cellValue) += 1
                End If
            End If
        Next

        Dim sb As New StringBuilder()
        For Each keyvalue As KeyValuePair(Of String, Integer) In dic
            sb.AppendLine(String.Format("{0}", keyvalue.Key, keyvalue.Value))
        Next

        For Each row As DataGridViewRow In datagridview2.Rows
            row.Cells(0).Value = sb.ToString()
            row.Cells(1).Value = dic.Count.ToString()
        Next
    End Sub