nethken
nethken

Reputation: 1092

Casting object causes exception

int total = 0;
for (int i = 0; i < dgvAttendance.Rows.Count; ++i)
{
    total += Convert.ToInt32(dgvAttendance.Rows[i].Cells[4]);
}
txtWH.Text = total.ToString();

How can I fix this exception occurring in my codes?

Upvotes: 2

Views: 89

Answers (2)

smilingkevin
smilingkevin

Reputation: 28

Have you tried:

total += Convert.ToInt32(dgvAttendance.Rows[i].Cells[4].Value);

I'm not sure what the class is of dgvAttendance, but if it's a DataGridView then what you're accessing with Cells[4] is the DataGridViewCell, not the value within.

Upvotes: 1

ChrisC73
ChrisC73

Reputation: 1853

You need to convert the text of the cell, not the cell itself:

total += Convert.ToInt32(dgvAttendance.Rows[i].Cells[4].Text);

Upvotes: 1

Related Questions