DannyDSB
DannyDSB

Reputation: 145

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 :)

Upvotes: 1

Views: 1082

Answers (1)

KishanRSojitra
KishanRSojitra

Reputation: 277

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));

Upvotes: 1

Related Questions