how to sum the data from datagridview not only for one value but foreach data(1000 numbers) from one specific column with the same number and show the result in other datagridview column( thx for help!) For example I use the excel table to read the Data
Asked
Active
Viewed 266 times
0
-
2Possible duplicate of [how I can show the sum of in a datagridview column?](https://stackoverflow.com/questions/3779729/how-i-can-show-the-sum-of-in-a-datagridview-column) – Kilazur Feb 18 '19 at 15:35
-
1[Also related here](https://stackoverflow.com/a/33399630/3773066) I've provided an answer if you want something more like Excel's behavior. – OhBeWise Feb 19 '19 at 17:42
1 Answers
0
Start by using a variable to which you assign 0. For each row of the DataGridView, get the value at the desired column and sum it up. Then use that value to populate the desired cell.

CedL
- 113
- 2
- 13
-
thx for help I understand what you mean literally but how to implement it without errors double n=1,435; and then foreach? {value in dgv.Nameof.Rows[4]} do i need to use index ? or name.. do or if .. how is the syntax? – Alex Feb 18 '19 at 15:54
-
@Alex Don't use "Nameof". Instead, use `dgv.Rows[index].Cells[4].Value`. This way, you get the value in the cell. If you don't want to use an index, you can always use a ForEach on the rows as well. So basically `For Each row in dgv.Rows` and then the other foreach inside that one would be like `For Each c in row.Cells[4].Value` – CedL Feb 18 '19 at 16:43
-
I have another problem with index Im getting the sum only for the first row but i need for each row in my datagridview !?my code: foreach (DataGridViewRow item in dataGridView1.Rows) { int i = item.Index; dataGridView1.Rows[i].Cells[3].Value = Double.Parse(dataGridView1.Rows[i].Cells[1].Value.ToString()) - Double.Parse(dataGridView1.Rows[i].Cells[2].Value.ToString()); } – Alex Feb 20 '19 at 13:41
-
Get rid of `int i = item.Index;` and replace all the `dataGridView1.Rows[i]` by `item`. In this ForEach loop (and all ForEach loop) you have access to **EACH** item **IN** what you are asking to loop in. Here, you are going through each _Rows_ of the _DataGridView._ So as you decided, the items will be a _DataGridViewRow_. Since you have access directly to the item with your variable _item_, then you can directly act on it. I have a feeling the problem comes from the index, since it's not RowIndex. – CedL Feb 20 '19 at 16:31
-
-
and now am getting this Exception: System.NullReferenceException' occurred in test2.exe... Troubleshooting tips: Check to determine if the object is null before calling the method. Use the"new" keyword to create an object instance. Get general help for this exception. – Alex Feb 21 '19 at 10:07