• We just launched and are currently in beta. Join us as we build and grow the community.

How to Calculate Two Columns in DataGridView

plot1

Anime Subreddit Admin
P Rep
0
0
0
Rep
0
P Vouches
0
0
0
Vouches
0
Posts
126
Likes
180
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 200 XP
In my previous tutorial using DataGridView Control I explained on “How to Differentiate Two Cell Values in DataGridView Control”. This time I will teach you on how to calculate two columns in DataGridView Control.

This tutorial is very useful if you want to make a total of the two columns. For example a total of “Qty” and “Sales Price” Column.

Additionally, we will make a total of the “Amount” column.

To achieve this all you have to do is trigger the CellEndEdit Events.

  1. Private

    Sub

    InvoiceDetailsDataGridView_CellEndEdit(

    ByVal

    sender As

    Object

    , ByVal

    e As

    System.

    Windows

    .

    Forms

    .

    DataGridViewCellEventArgs

    )

    Handles

    InvoiceDetailsDataGridView.

    CellEndEdit
  2. Dim

    InvoiceDetails As

    DataGridView =

    DirectCast

    (

    sender, DataGridView)

  3. If

    IsDBNull(

    InvoiceDetails(

    0

    , e.

    RowIndex

    )

    .

    Value

    )

    Then

    Exit

    Sub

  4. InvoiceDetails(

    "Amount"

    , e.

    RowIndex

    )

    .

    Value

    =

    InvoiceDetails(

    "Qty"

    , e.

    RowIndex

    )

    .

    Value

    *

    InvoiceDetails(

    "SalesPrice"

    , e.

    RowIndex

    )

    .

    Value

  5. If

    (

    e.

    ColumnIndex

    =

    2

    Or

    e.

    ColumnIndex

    =

    4

    )

    And

    InvoiceDetails.

    Rows

    .

    Count

    >

    0

    Then
  6. TotalTextBox.

    Text

    =

    Total(

    )

    .

    ToString
  7. End

    If
  8. End

    Sub

This assume that the name of your DataGridView Control is InvoiceDetailsDataGridView and you have change the name of the column to “Qty”, “SalesPrice”, and “Amount”.

[inline:datagridview_columns_properties.jpg=DataGridView Column Properties]

e.

ColumnIndex

=

2

Or

e.

ColumnIndex

=

4

assumes that “Qty” column has an index equals to 2 and “Amount” equals to 4.

Now here’s the Total function.

  1. Private

    Function

    Total(

    )

    As

    Double
  2. Dim

    tot As

    Double

    =

    0
  3. Dim

    i As

    Integer

    =

    0

  4. For

    i =

    0

    To

    InvoiceDetailsDataGridView.

    Rows

    .

    Count

    -

    1
  5. tot =

    tot +

    Convert.

    ToDouble

    (

    InvoiceDetailsDataGridView.

    Rows

    (

    i)

    .

    Cells

    (

    "Amount"

    )

    .

    Value

    )
  6. Next

    i

  7. Return

    tot
  8. End

    Function

What you need here is a DataGridView Control and a TextBox named “TotalTextBox”.

 

452,292

323,341

323,350

Top