c# - DataGridView 中的计算列绑定(bind)到一个对象

标签 c# winforms datagridview datagridviewcolumn

我的 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/

相关文章:

c# - 如何计算datagridview中的行并将重复行视为单个行?

c# - DataContractAttribute、IExtensibleDataObject、ExtensionDataObject 上的错误

c# - 在 c# 中的 Windows 窗体上添加项目和扩展 checkedlistbox 的集合列表的问题

c# - DataGridView ScrollBars 在 Thread 之后不工作

c# - 如何将图像添加到 DataGridView 中的单个特定单元格?

c# - 帮助设计订单管理器类

c# - 将静态参数转换为哈希表并与 lambda 搜索一起使用

c# - Xamarin.Forms ListView 绑定(bind)问题

c# - 如何在C#中控制datagridview光标移动

c# - 了解 C# 属性的工作原理