簡體   English   中英

如何將 DataGridView 單元格值與 ComboBox 標准相加?

[英]How to sum DataGridView cell value with ComboBox criteria?

我在form1中有一個 DataGridView ,在form2中有一個combobox1textbox2 我將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

你似乎有一個額外的循環。 我也不知道我們是在使用Integer還是Double值。 我在代碼中使用了 Double,但您可以輕松地將其更改為 Integer。 如果您確定這些值都是整數,則不要使用Convert.To使用簡單優化的 vb 特定CInt .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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM