开发者

How to do simple math in datagridview

开发者 https://www.devze.com 2022-12-27 00:03 出处:网络
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 exc

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?


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


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.");
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消