合并datagridview visual basic.net 2008中的项目

时间:2014-11-10 17:02:37

标签: vb.net

 Dim X As String
 Dim V, Q, Y As Double
DGV.ColumnCount = 3
 con.Open()
cmd = New SqlCommand("select Name,Price from Items where Name ='" & ListItems.SelectedItem & "'", con)
DR = cmd.ExecuteReader
While DR.Read()
    ' Q = Val(Qty.Text)
    X = (DR("Name").ToString())
    Y = Val((DR("Price").ToString()))
    V = Q * Y
    Dim row As String() = New String() {Q, X, V}
    DGV.Rows.Add(row)

我正在使用visual basic.net,如果我在datagridview中有类似的项目,如下所示 例如

1 hot dog 5 $
2 hot dog 10 $
5 hot dog 20 $

我们如何将它们合并为一行

8热狗40 $

1 个答案:

答案 0 :(得分:0)

所以你有“名称”和“价格”列。从您的代码下的文本中我看到该名称将是“5 hotdog”,Price将是“20 $”。我不知道他们是否按照这种方式进行格式化,但我会假设这样。

因此,您首先要做的是计算“总”行中您想要的值。由于您的初始号码后面有“热狗”或字符串,因此我们希望为每个值获取该号码。我们将循环,评估该数字,并总结。我们将对价格列执行相同操作,但我们将删除字符串中的“$”。再说一遍,我在这里做了很多假设。

    Dim nameTotal As Integer = 0
    Dim priceTotal As Integer = 0

    'loop through each row of the DGV
    For Each row As DataRow In DGV.Rows

        'evaluate value in current row
        Dim str_nameValue As String = row.Item("Name").ToString()
        str_nameValue = str_nameValue.Remove(" hot dog")

        'or if there are other string attached, remove those from the str_nameValue here to get an integer
        'processing stringcode here...

        'add to name total 
        nameTotal += CInt(str_nameValue)

        'do the same for the other column
        Dim str_priceValue As String = row.Item("Price").ToString()
        str_priceValue = str_priceValue.Remove("$")

        'sum
        priceTotal += CInt(str_priceValue)
    Next

    'for loop is finished, add a new row with the values 

    'add row to table with a parameter of total values, and an empty one for the second column 
    DGV.Rows.Add(nameTotal & " hot dog " & priceTotal & "$", " ")

您应该负责格式化字符串以满足您的需求。