CodyMan CodyMan - 2 months ago 7
Vb.net Question

How to sum multiple columns value of DataGridView

I'm doing one project for my institute, and I'm having problem while trying to sum DataGridView columns. I need to calculate Total Amount.

Here is my code:

Private Sub add()
Dim i As Integer = 0
dgvStock.Rows.Add()
dgvStock.Rows(dgvStock.RowCount - 1).Cells("srno").Value = txt_billno.Text
dgvStock.Rows(dgvStock.RowCount - 1).Cells("itemcode").Value = cmbItemCode.Text
dgvStock.Rows(dgvStock.RowCount - 1).Cells("itemname").Value = cmbItemName.Text
dgvStock.Rows(dgvStock.RowCount - 1).Cells("qty").Value = txtQty.Text
dgvStock.Rows(dgvStock.RowCount - 1).Cells("Rate").Value = txtRate.Text
dgvStock.Rows(dgvStock.RowCount - 1).Cells("Discount").Value = txtPerDisc.Text
dgvStock.Rows(dgvStock.RowCount - 1).Cells("PerTax").Value = txtPerVat.Text
txtAmount.Text = txtRate.Text * txtQty.Text
txtAmount.Text -= txtPerDisc.Text
' txtAmount.Text += txtPerDisc.Text / 100
dgvStock.Rows(dgvStock.RowCount - 1).Cells("Amount").Value = txtAmount.Text
txtGridAmt.Text = dgvStock.SelectedRows(0).Cells("Amount").Value
txtdiscRs.Text = dgvStock.SelectedRows(0).Cells("Discount").Value
txtVatRs.Text = dgvStock.SelectedRows(0).Cells("PerTax").Value
txtTotAmt.Text = txtGridAmt.Text
End Sub
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Try
add()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
'formclear()
End Sub


Here is snapshot of my program it will make my question clearer
http://postimg.org/image/9ztydl5j1

Answer

Your ways to add or subtract the values does not seem to be correct. Since .Text is a String, not an Integer. Try changing this:

txtAmount.Text = txtRate.Text * txtQty.Text
txtAmount.Text -= txtPerDisc.Text

To this:

txtAmount.Text = CStr(CInt(txtRate.Text) * CInt(txtQty.Text))
txtAmount.Text = CStr(CInt(txtAmount.Text) - CInt(txtPerDisc.Text))

--- EDIT ---

Try this instead:

Dim NewRow As String() = {"", "", "", "", "", "", "", ""}
dgvStock.Rows.Add(NewRow)

--- EDIT 2 ---

Well:

Dim TotalAmount As Integer = 0
For x = 0 To dgvStock.Rows.Count - 1
    TotalAmount += dgvStock.Rows(x).Cells("Amount").Value
Next

Before removing:

TotalAmount -= dgvStock.Rows(dgvStock.SelectedRows(0)).Cells("Amount").Value