【问题标题】:How to sum DataGridView cell value with ComboBox criteria?如何将 DataGridView 单元格值与 ComboBox 标准相加?
【发布时间】:2020-04-29 12:39:19
【问题描述】:

我在form1 和combobox1 和textbox2 在form2 中有一个DataGridView。我将combobox1 值与form1 DataGridView 匹配,并对DataGridView 特定单元格与combobox1 选定值进行总和。我的 ComboBox 的值是 1、2、3、4,当 ComboBox 选择的值与 DataGridView 值匹配时,我想要对 DataGridView 特定单元格求和,但我的代码对所有单元格求和。请建议我怎么做?

Private Sub cn()

    Dim totalcn As Double
    For Each rw As DataGridViewRow In Form1.DataGridView2.Rows
        If rw.Cells(2).Value = ComboBox1.Text Then

            'if you have the other column to get the result you  could add a new one like these above 
            For index As Integer = 0 To Form1.DataGridView2.RowCount - 1
                totalcn += Convert.ToInt32(Form1.DataGridView2.Rows(index).Cells(1).Value)
            Next
        End If           
    Next
    Label11.Text = totalcn.ToString

End Sub

【问题讨论】:

    标签: vb.net winforms datagridview


    【解决方案1】:

    你似乎有一个额外的循环。我也不知道我们是在使用Integer 还是Double 值。我在代码中使用了 Double,但您可以轻松地将其更改为 Integer。如果您确定这些值都是整数,请使用简单优化的 vb 特定 CInt 而不是 Convert.To。更安全的是.TryParse。

    Private Sub cn()
        Dim totalcn As Double
        Dim cellDoub As Double
        For Each rw As DataGridViewRow In Form1.DataGridView2.Rows
            If rw.Cells(2).Value.ToString = ComboBox1.Text Then
                If Double.TryParse(rw.Cells(1).Value.ToString, cellDoub) Then
                    totalcn += cellDoub
                End If
            End If
        Next
        Label11.Text = totalcn.ToString
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-05
      • 2023-02-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多