Click here to Skip to main content
14,327,583 members
Rate this:
Please Sign up or sign in to 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 17-Jul-16 23:54pm

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100