Home > Software design >  how to sum values between columns in grid view with IFCondition?
how to sum values between columns in grid view with IFCondition?

Time:06-02

i have 3 columns in gridview, Column_A, Column_B and Column_total. then i do simple calculation between Column_A and Column_B and put it in Column_total.. example: when i enter value 1 in row Column_A and 1 in row Column_B, Column_total displays result 2. this simple code works:

private void Gdv_CellEndEdit(object sender, GridViewCellEventArgs e)
    {
        foreach (GridViewDataRowInfo Val in Gdv.SelectedRows)
        {
            Val.Cells["Column_Total"].Value =  Convert.ToInt32(Val.Cells["Column_A"].Value)   Convert.ToInt32(Val.Cells["Column_B"].Value);
        }
    }


but in Column_total still showing result when I delete value in Column_A..

What I want, Column_total shows result when I enter value in Column_A, then when I delete value in Column_A then Column_total will return empty and won't show any result.. anyone can help?

CodePudding user response:

Your method is not being recalled to reassign the updated value, I can only guess your .value is a string as you are using convert and didn't specify.

private void Gdv_CellEndEdit(object sender, GridViewCellEventArgs e)
{
    bool _; /*Throw away value true/false output not needed, 
              prevents compiler warning.*/

    foreach (GridViewDataRowInfo Val in Gdv.SelectedRows)
    {
        _ = int.TryParse(Val.Cells["Column_A"].Value, out a);
        _ = int.TryParse(Val.Cells["Column_B"].Value, out b);

        Val.Cells["Column_Total"].Value = (a != 0 || b != 0) ? (a   b) : "";

        //If a or b is not 0, as int cannot be null; will sum(a b), else return "" empty.
        //Can change the or || to && if you require both to have values > 0.
    }
}

CodePudding user response:

finally..
agree with @JohnG, to solve my question problem is to use column expression.
this is the last code snippet of my project :

  // Create second column.
  DataColumn Col_A = new DataColumn();
  Col_A .DataType = System.Type.GetType("System.Decimal");
  Col_A .ColumnName = "Column_A";

  // Create second column.
  DataColumn Col_Total = new DataColumn();
  Col_Total .DataType = System.Type.GetType("System.Decimal");
  Col_Total .ColumnName = "Column_total";
  Col_Total .Expression = "Column_A * Column_B";

  // Add columns to DataTable.
  dt.Columns.Add(Col_A);
  dt.Columns.Add(Col_Total);

  DataView view = new DataView(dt);
  dgv.DataSource = view;

I added 2 new columns named "Col_A" and "Col_Total" and in the summation column, the column "Column_B" is obtained from the gridview which displays the data source from mysql.

it really works, and I don't know if there's anything better than this?

Thank you for those of you who have answered my previous question.

  • Related