Computing columns in a DataGridView bound to an object

My user interface consists of datagridview ( AutoCreateColumns= false) bound to a list of my business objects. Suppose my object contains 2 columns - Price and quantity - and I would like to add a new column in my grid - Total - what value will be calculated - Price * Quantity, BUT without changing my business object.

Is it possible?

+5
source share
2 answers

Yes.

You can add unrelated columns to the grid programmatically, and you populate the column cells either using events.

: RowsAdded CellFormatting. CellValueChanged . CellFormatting , , , , , .

-

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);
    }
}

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

+5

, .

0

All Articles