aliprogrammer
aliprogrammer

Reputation: 197

Sum of column values in C#

I use these following code to calculating summation of a specific row in the database and show it in a new row under that intention column. but i will encounter an error.

Object reference not set to an instance of an object

Please help me to solve this.

Thanks in advance.

int sum = 0;

for (int i = 0; i < dt.Rows.Count; i++)
{
    sum += int.Parse(dataGridView1.Rows[i].Cells["Fee"].Value.ToString());
}

DataSet ds = new DataSet();
adapter.Fill(ds);
DataRow row = ds.Tables["Entry"].NewRow();
ds.Tables["Entry"].Rows.Add(row);

I want to know how can I see the sum in a new row.

Upvotes: 0

Views: 4500

Answers (6)

bresleveloper
bresleveloper

Reputation: 6070

It can also happen if the DB returns null for one "FEE" cell. Run it and see where are you exactly and look at the values, if you see a null you'll need if != null.

Upvotes: 0

Deepesh
Deepesh

Reputation: 5604

Though your question is not very clear but Check out the loop either access value from datatable or from grid Like

for (int i = 0; i < dt.Rows.Count; i++)
{
   if (dt.Rows[i]["Fee"].Value !=null)
   sum += int.Parse(dt.Rows[i]["Fee"].Value.ToString());
}

And also make sure dt.Rows[i]["Fee"] does not contain null values Even you can use Compute method to do the sum.

Upvotes: 1

John Woo
John Woo

Reputation: 263703

i think the error is in the loop statement:

Instead of:

for (int i = 0; i < dt.Rows.Count; i++)
{
    sum += int.Parse(dataGridView1.Rows[i].Cells["Fee"].Value.ToString());
}

use this:

for (int i = 0; i < dt.Rows.Count - 1; i++)
{
    sum += int.Parse(dataGridView1.Rows[i].Cells["Fee"].Value.ToString());
}

you are starting at Index zero so you should deduct one for the total number of rows. It will return Object reference not set to an instance of an object when it reaches on:

sum += int.Parse(dataGridView1.Rows[dt.Rows.Count].Cells["Fee"].Value.ToString());

because such row does not exists.

UPDATE 1

after the loop, insert this statement:

dataGridView1.Rows.Add("", "", sum)

UPDATE 2

int sum = 0;

for (int i = 0; i < dt.Rows.Count - 1; i++)
{
    sum += int.Parse(dataGridView1.Rows[i].Cells["Fee"].Value.ToString());
}

DataSet ds = new DataSet();
adapter.Fill(ds);

DataRow row = ds.Tables["Entry"].NewRow();
row[0] = "";
row[1] = "";
row[2] = sum;
ds.Tables["Entry"].Rows.Add(row);

Upvotes: 3

Vetrivel mp
Vetrivel mp

Reputation: 1224

you can use compute method in datatable. get result from compute method then create new row from datatable then assign to appropriate field. then add the new row to datatable.

Upvotes: 1

Ezi
Ezi

Reputation: 2210

'ds' doesn't have a table 'Entry', that's why you get a 'Object reference not set to an instance of an object' error.

Upvotes: 2

Petur Subev
Petur Subev

Reputation: 20193

I suggest you to use the debugger and see where exactly this error occurs :)

Upvotes: 0

Related Questions