Click here to Skip to main content
14,766,117 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:
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());
   
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.
Mithlesh Shaw 18-Jul-16 6:24am
   
replace if statement with this one and check
if (item.Cells[CELL_INDEX] != null
&& item.Cells[CELL_INDEX].Value != null && item.Cells[CELL_INDEX].Value != System.DBNull.Value)
Boopalslm 18-Jul-16 6:28am
   
i am change your if statement line but
before run error is came

invalid expression term '}'
Boopalslm 18-Jul-16 6:30am
   
k its working fine , but shown value zero(0), but my grid view cells having some values.
Mithlesh Shaw 18-Jul-16 6:31am
   
you have missed the '}'
here is the full code

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 && item.Cells[CELL_INDEX].Value != System.DBNull.Value)
val += Convert.ToDecimal(item.Cells[CELL_INDEX].Value);
}
MessageBox.Show(val.ToString());
Boopalslm 18-Jul-16 6:33am
   
Sir thanks a lot working super and again thanks.

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