DannyDSB DannyDSB - 11 days ago 6
C# Question

Calculate values in 2 DataGridView cells - C#

I can't figure out how to solve this. I wanna calculate the sum of 2 cells in a DataGridView, divide their sum by 2 and then write that value inside a specific cell. Whenever I click the button it show me this error:


Unable to cast object of type 'System.Windows.Forms.DataGridViewTextBoxCell' to type 'System.IConvertible'.


How do I solve this error? My code is this:

private void button4_Click(object sender, EventArgs e)
{
int total;
foreach(DataGridViewColumn column in dataGridView1.Columns)
{
total = dataGridView1.Rows.OfType<DataGridViewRow>().Sum(r => Convert.ToInt32(r.Cells[2]));
dataGridView1.Rows[4].Cells[column.Index].Value = total;
}
}


Please help me! Thanks :)

Answer

Because you are converting Cell to integer and that is no possible use Cell.Value to get cell value.

Change

total = dataGridView1.Rows.OfType<DataGridViewRow>().Sum(r => Convert.ToInt32(r.Cells[2]));

To this

total = dataGridView1.Rows.OfType<DataGridViewRow>().Sum(r => Convert.ToInt32(r.Cells[1].Value));