How to Multiply Data Gridview two columns and show

2019-08-01 18:23发布

问题:

I have a gridview (Order) with three columns:

  1. Price
  2. Quantity
  3. Total

I want to multiply Price with Quantity and show the result in Total column of dataGridview.

Remember: my dataGridview isn't bind with any table.

I am trying this code to achieve my goal but this isn't working means value isn't being returned:

private void totalcal()
{
    // is the foreach condition true? Remember my gridview isn't bound to any tbl
    foreach (DataGridViewRow row in gvSale.Rows)
    {
        int a = Convert.ToInt32(row.Cells[3].Value) *     Convert.ToInt32(row.Cells[4].Value);  // value is null why??
        row.Cells[5].Value = a;
    }
}

This is the method which I am calling on a button click. (It is not working reason define inside of my code above)

And plus I want to know which is the suitable Datagridview event for this calculation?? I don't want to calculate the total on button click

回答1:

try

int.Parse(row.Cells[3].Value.toString()) * int.Parse(row.Cells[4].Value.toString())

insted of

Convert.ToInt32(row.Cells[3].Value) * Convert.ToInt32(row.Cells[4].Value)

And you know you can call this method anytime, if you dont want it to be with button click. Call it after gvSale's row populating operations finished.

EDIT

I guess you want the calculations to be done while the user is entering Price or Quanitity. For that you need to write a EditingControlShowing method for your datagridview. Here's a piece of code. I tested it actually and got it working.

Add this code in your main class definition after InitializeComponent(); line

gvSale.EditingControlShowing += new System.Windows.Forms.DataGridViewEditingControlShowingEventHandler(this.gvSale_EditingControlShowing);

And then add this methods :

TextBox tb = new TextBox(); // this is just a textbox to use in editing control
int Price_Index = 3; // set this to your Price Column Index
int Quantity_Index = 4; // set this to your Quantity Column Index
int Total_Index = 5; // set this to your Total Column Index

private void gvSale_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
  if (gvSale.CurrentCell.ColumnIndex == Price_Index || gvSale.CurrentCell.ColumnIndex == Quantity_Index)
  {
    tb = e.Control as TextBox;
    tb.KeyUp += new KeyEventHandler(Calculate_Total);
  }
}

private void Calculate_Total(object sender, KeyEventArgs e)
{
  int Price_Value = 0;
  int Quantity_Value = 0;
  int.TryParse(gvSale.CurrentCell.ColumnIndex != Price_Index ? gvSale.CurrentRow.Cells[Price_Index].Value.ToString() : tb.Text, out Price_Value);
  int.TryParse(gvSale.CurrentCell.ColumnIndex != Quantity_Index ? gvSale.CurrentRow.Cells[Quantity_Index].Value.ToString() : tb.Text, out Quantity_Value);
  gvSale.CurrentRow.Cells[Total_Index].Value = Price_Value * Quantity_Value;
}