从DataGridView中删除重复项,但要继续计数吗?

时间:2018-12-28 17:02:14

标签: vb.net

我有一个datagridview,其中包含我从SQL Server中提取的数据。它返回一些重复的数据。我想删除所有重复项,但要保留每个唯一项的数量。这是数据外观的示例...

sample

For intI = DataGridView1.Rows.Count - 1 To 0 Step -1
    For intJ = intI - 1 To 0 Step -1
        If DataGridView1.Rows(intI).Cells(1).Value = 
DataGridView1.Rows(intJ).Cells(1).Value AndAlso 
DataGridView1.Rows(intI).Cells(3).Value = 
DataGridView1.Rows(intJ).Cells(3).Value Then
    DataGridView1.Rows.RemoveAt(intI)
     Exit For
  End If
Next
Next

因此,我可以删除所有重复项,但是我希望能够最终统计所有项目,包括重复项。例如,有5个CA,我想删除4个,只剩下1个唯一的CA,但是我想证明我的datagridview中有5个CA,位于加利福尼亚旁边。

所以最后,我希望datagridview具有类似的内容:

状态|短

加利福尼亚| 5

这是我的查询:

DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SELECT
    States , Shorts 
FROM
    DAT.States
        INNER JOIN
    DATR.[Shorts]
WHERE @StartDate IS NULL

谢谢您的帮助!

编辑:

我想出一种将GridView1计入GridView2的方法,但是我不确定代码。也许我可以在这部分上获得一些帮助?

For i As Integer = DataGridView1.RowCount - 1 To 1 Step -1
    For j As Integer = DataGridView2.RowCount - 1 To 1 Step -1
        'If Grid2.Row(j).Cells(1).Value = Grid1.Rows(i).Cells(1).Value Then
        '   Grid2 already has that value, +1 to Column 2 of Cell(j)
        '   Delete row(i)
        'Else
        'Value does not exist, add row(i) into Grid2, and in the 2nd column of Grid2, the count is 1
        'End If
    Next
Next

GridView2的最终结果将类似于:

sample

这是我想出的代码,它试图计算第1列中的状态,然后将其删除并将其添加到Grid2中,但是它不起作用...

Dim Counts As Integer = 0
Dim State As String = ""
Dim CurLoop As Integer = 0

        Do Until CurLoop > DataGridView1.RowCount - 1
            State = DataGridView1.Rows(CurLoop).Cells(0).Value
            For i As Integer = DataGridView1.RowCount - 1 To 1 Step -1
                If DataGridView1.Rows(i).Cells(0).Value = State Then
                    Counts += 1
                    DataGridView1.Rows.RemoveAt(i)
                End If
            Next
            DataGridView2.Rows.Add(State, Counts)
            State = ""
            Counts = 0
            CurLoop += 1
        Loop

1 个答案:

答案 0 :(得分:0)

我已经找到了我自己问题的答案。这不是最漂亮的解决方案,但可以。如果其他任何人需要这样的东西,这就是我所做的...

  <tr>
            <td style="border: 1px solid black;"><img src='https://i.ibb.co/6DsDQQ3/logo.png'  style="height: 200px;"></td>

            <td style="border: 1px solid black;"><img src="https://i.ibb.co/0n2zfJg/product-features.png"  style="height: 200px;"></td>

            <td style="border: 1px solid black;"><img src="https://i.ibb.co/6BRPLvs/intro-bg.jpg"  style="height: 200px;"></td>

        </tr>

由于某种原因,无论Grid1的第一行是什么,它总是比应该的值低1,所以我在末尾加1。