EB.
EB.

Reputation: 2757

How to do simple math in datagridview

I have a datagridview with 9 columns. I am simply trying take the value in column 5 and subtract it from column 6, then display the result in column 9. It seems simple enough, I know it's done in excel all the time. But I just cannot figure this out. Do I need to create a new class with a method called calculate columns? Or does the datagridview class have something already built in that can handle this?

Upvotes: 0

Views: 5327

Answers (3)

Flynn1179
Flynn1179

Reputation: 12075

Bind your DataGridView to a DataTable, and give the column a relevant expression. Try extrapolating this example:

        DataTable table = new DataTable();
        table.Columns.Add("Column1", typeof(int));
        table.Columns.Add("Column2", typeof(int));
        table.Columns.Add("Column3", typeof(int), "Column1+Column2");
        dataGridView1.DataSource = table;

where 'dataGridView1' is a typical DataGridView control.

Upvotes: 1

public void dataGridView_Cellformatting(object sender, DataGridViewCellFormattingEventArgs args)
{
    if(args.ColumnIndex == 9) //Might be 8, I don't remember if columns are 0-based or 1-based
    {
        DataGridViewRow row = dataGridView.Rows[e.RowIndex];
        args.Value = (int)row.Cells[6].Value - (int)row.Cells[5].Value;
    }
}

Links: CellFormatting event, DataGridViewcellFormattingEventArgs

Upvotes: 1

Anthony Pegram
Anthony Pegram

Reputation: 126804

The sample code below shows how you can retrieve values at a given position (column and row, 0-indexed) and then attempt to convert those values to numbers. You can then store the calculation back into another cell within the DataGridView.

object value1 = dataGridView1[4, 0].Value;
object value2 = dataGridView1[5, 0].Value;

int val1, val2;
if (int.TryParse(value1.ToString(), out val1) && int.TryParse(value2.ToString(), out val2))
{
    dataGridView1[8, 0].Value = val1 - val2;
}
else
{
    MessageBox.Show("cannot subtract, invalid inputs.");
}

Upvotes: 1

Related Questions