5

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?

Sujith H S
  • 477
  • 8
  • 18
DreadAngel
  • 772
  • 11
  • 30

2 Answers2

5

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

A G
  • 21,087
  • 11
  • 87
  • 112
  • Thanks, this approach seems very close to what I need. Even data refresh works. Thanks a lot. – DreadAngel May 11 '12 at 13:53
  • 1
    A little mention - for Value field of DataGridViewCellFormattingEventArgs parameter should be assigned only **string** values – DreadAngel May 11 '12 at 14:31
  • ok.. hmm.. is the cell blank when its something else? Does it not show the toString() representation of the object? – A G May 11 '12 at 16:59
  • No, just enough to take the string representation of what it's need to be show. – DreadAngel May 12 '12 at 11:20
0

No, not without editing your object.

MrWuf
  • 1,478
  • 1
  • 14
  • 30