我的 UI 包含一个绑定(bind)到我的业务对象列表的数据 GridView (AutoCreateColumns= false
)。假设我的对象包含 2 列 - 价格和数量 - 我想在我的网格中添加一个新列 - 总计 - 将计算哪个值 - 价格*数量,BUT 没有修改我的业务对象。
这可能吗?
最佳答案
是的。
您可以通过编程方式将未绑定(bind)的列添加到网格,并使用事件填充列的单元格。
填充未绑定(bind)列内容的主要方法有两种:处理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
关于c# - DataGridView 中的计算列绑定(bind)到一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10551607/