簡體   English   中英

如何在DataGridView中執行簡單的數學運算

[英]How to do simple math in datagridview

我有9列的datagridview。 我只是嘗試將第5列中的值減去第6列中的值,然后在第9列中顯示結果。這似乎很簡單,我知道它一直在excel中完成。 但我只是無法弄清楚。 我是否需要使用一種稱為“計算列”的方法來創建新類? 還是datagridview類已經內置了可以處理此問題的東西?

下面的示例代碼顯示了如何檢索給定位置(列和行,索引為0)的值,然后嘗試將這些值轉換為數字。 然后,您可以將計算結果存儲回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.");
}
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;
    }
}

鏈接: CellFormatting事件, DataGridViewcellFormattingEventArgs

將您的DataGridView綁定到一個DataTable,並為該列提供一個相關的表達式。 嘗試外推此示例:

        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;

其中“ dataGridView1”是典型的DataGridView控件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM