Question calculate the value of one cell by values of 2 other cells

pooya1072

Well-known member
Joined
Jul 5, 2012
Messages
84
Programming Experience
Beginner
hi
i have a datagridview in my form . in very simple state : i want to set the value of cell(1) of rows(1) equal to sum of values of cell(2) and cell(3) of rows(1) ... in other word :
VB.NET:
Dgv1.Rows(1).cell(1).value=Dgv1.Rows(1).cell(2).value + Dgv1.Rows(1).cell(3).value
my problem is that i want each time i input a value in cells(2) or cells(3) then the value of cells(1) change to result .
please think about a large size of data.this example is very simple .
 
Hi,

You can do this by coding the CellValueChanged event of the DataGridView, checking for whether the ColumnIndex of the cell changing is either 2 or 3 and then update cell 1 of the CurrentRow. Have a look at this quick example:-

VB.NET:
Public Class Form1
 
  Private Sub Form1_Shown(sender As Object, e As System.EventArgs) Handles Me.Shown
    AddHandler DataGridView1.CellValueChanged, AddressOf DataGridView1_CellValueChanged
  End Sub
 
  Private Sub DataGridView1_CellValueChanged(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs)
    If e.ColumnIndex = 2 Or e.ColumnIndex = 3 Then
      DataGridView1.CurrentRow.Cells(1).Value = CDbl(DataGridView1.CurrentRow.Cells(2).Value) + CDbl(DataGridView1.CurrentRow.Cells(3).Value)
    End If
  End Sub
End Class

Notice that I add the handler for the CellValueChanged event when the form has completed loading. This is so that you do not get Object Reference Errors during the creation of the DataGridView.

Hope that helps.

Cheers,

Ian
 
thanks IanRyder

i want to create a program like excel . (but only a part of excel ) you can run excel and then define a equation for a cell .
i want after run my program i specify the equation of one cell (my first example ) .
the main problem is that i want define it after running the program .
 
in the example i said cell(5)=cell(3)+cell(4) .... i want select cell(3) and cell(4) after running the program . like excel
 
Hi,

To create an Excel like component within .NET sounds like a massive undertaking so I am not even going to try and demonstrate where to start. That will be up to you. After a quick look on the net, the two commercial products that tend to crop up are:-

SpreadsheetGear and Spread.NET

Have a search for yourself to see if any of these are of interest to you.

Cheers,

Ian
 
Back
Top