如何在数据网格视图的两列上执行乘法并在第三列中分配它?

时间:2013-11-28 06:18:04

标签: c# winforms datagridview datagridviewcolumn

以下是我的代码,我正在尝试显示Rate * Supply列值的乘法并将其分配到数据网格视图中的Amount列:

try
{
    Query = "Select  id,Code,Description,Rate,Cust_Id,Supply,Empty,Amount,Received from Items ";
    adap = new SQLiteDataAdapter(Query, GlobalVars.conn);
    ds = new DataSet();
    adap.Fill(ds, "Items");
    dtgVOuchers.DataSource = ds.Tables[0];

    ds.Tables[0].Columns["Amount"].DefaultValue = (ds.Tables[0].Columns["Rate"].DefaultValue) * (ds.Tables[0].Columns["Supply"].DefaultValue); //error

    //dtgVOuchers.Rows.Clear();
    ds.Tables[0].Clear();
    dtgVOuchers.Refresh();
}

有谁知道如何在数据网格视图中完成此功能? 。 。请帮我纠正这段代码。感谢

4 个答案:

答案 0 :(得分:0)

只需使用查询

Select  id,Code,Description,Rate,Cust_Id,Supply,Empty,isnull(Rate,0)*isnull(Supply,0) as [Amount],Received from Items 

答案 1 :(得分:0)

DataTable myDataTable = new DataTable();

      DataColumn quantityColumn = new DataColumn("Quantity");
      DataColumn rateColumn = new DataColumn("Rate");
      DataColumn priceColumn = new DataColumn ("Price");

      quantityColumn.DataType = typeof(int);
      rateColumn.DataType = typeof(int);

      myDataTable.Columns.Add(quantityColumn);
      myDataTable.Columns.Add(rateColumn);
      myDataTable.Columns.Add(priceColumn);

      //Set the Expression here
      priceColumn.Expression = "Quantity * Rate";

答案 2 :(得分:0)

使用以下代码..运行循环以更新所有行中的Amount列

注意:虽然这种方法不是首选,因为它会影响性能。所以在sql查询中进行此计算。我不明白在SQL查询中不执行munltiplication背后的原因..

  foreach (DataRow row in ds.Tables[0].Rows)
       {
          row["Amount"]= Convert.ToDecimal(row["Rate"])* Convert.ToDecimal(row["Supply"]);
          ds.Tables[0].AcceptChanges();        
       } 
    dtgVOuchers.DataSource = ds.Tables[0];
    dtgVOuchers.Refresh();

答案 3 :(得分:0)

            foreach (DataGridViewRow row in dtgVOuchers.Rows)
            {
                row.Cells[dtgVOuchers.Columns["Amount"].Index].Value = (Convert.ToDouble(row.Cells[dtgVOuchers.Columns["Rate"].Index].Value) * Convert.ToDouble(row.Cells[dtgVOuchers.Columns["Supply"].Index].Value));

            }