Click here to Skip to main content
15,507,388 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How to get data grid view sum values for label in c# win forms 2010, but my data grid view some cells are empty.

What I have tried:

How to calculate sum of column in data grid view empty cells.
Posted
Updated 22-Feb-20 19:24pm

1 solution

Try below code:
C#
decimal val=0;
foreach (DataGridViewRow item in dataGridView1.Rows)
{
   if (item.Cells[1] != null && item.Cells[1].Value != null)
        val += Convert.ToDecimal(item.Cells[1].Value);
}
MessageBox.Show(val.ToString());
 
Share this answer
 
Comments
Boopalslm 18-Jul-16 6:13am    
Error is came for below line

val += Convert.ToDecimal(item.Cells[1].Value);

Input string was not in a correct format.
Mithlesh Shaw 18-Jul-16 6:16am    
Here 1 is the cell index. In your program you put your cell index. Cell index starts with 0.
Boopalslm 18-Jul-16 6:19am    
i know, but my cell index is 9, i am set 9 for cell index, in 9th cell some empty cell are available so below error is came.

Object cannot be cast from DBNull to other types.
Mithlesh Shaw 18-Jul-16 6:18am    
decimal val=0;
const int CELL_INDEX = 1;//Your column index
foreach (DataGridViewRow item in dataGridView1.Rows)
{
if (item.Cells[CELL_INDEX] != null && item.Cells[CELL_INDEX].Value != null)
val += Convert.ToDecimal(item.Cells[CELL_INDEX].Value);
}
MessageBox.Show(val.ToString());
Boopalslm 18-Jul-16 6:21am    
Same error is came.

val += Convert.ToDecimal(item.Cells[9].Value);

Object cannot be cast from DBNull to other types.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900