Search code examples
c#winformsdatagridviewdatagridviewcolumn

Calculation Columns in DataGridView bounded to an object


My UI consist of a datagridview (AutoCreateColumns= false) bound to a list of my business objects. Let's assume my Object contains 2 columns - Price and Quantity - and I'd want to add a new column in my grid - Total - which value will be calculated - Price*Quantity, BUT with no modification of my Business object.

Is it possible?


Solution

  • Yes.

    You can add unbound columns to a grid programmatically, and you populate the column’s cells either using events.

    There are two primary ways to populate the contents of unbound columns: handling the RowsAdded event or handling the CellFormatting event. If the grid is editable CellValueChanged also needs to be handled. The CellFormatting event can also be used to transform values as they are presented in a cell to something different than the value that is actually stored in the data that sits behind the grid.

    Code Sample -

    private void OnCellFormatting(object sender,
       DataGridViewCellFormattingEventArgs e)
    {
    
        if (e.ColumnIndex == grid.Columns["Unbound"].Index)
        {
           e.FormattingApplied = true;
           DataGridViewRow row = grid.Rows[e.RowIndex];
           e.Value = string.Format("{0} : {1}",
              row.Cells["SomeColumn1"].Value,
              row.Cells["SomeColumn2"].Value);
        }
    }
    
    private void OnRowsAdded(object sender,
       DataGridViewRowsAddedEventArgs e)
    {
    
       for (int i = 0; i < e.RowCount; i++)
       {
          DataGridViewRow row = grid.Rows[e.RowIndex + i];
          row.Cells["Unbound"].Value = string.Format("{0} : {1}",
             row.Cells["SomeColumn1"].Value,
             row.Cells["SomeColumn2"].Value);
        }
    }
    

    More in detail - http://www.informit.com/articles/article.aspx?p=446453&seqNum=5