简体   繁体   English

如何在DataGridView中显示数据之前重新格式化/转换数据查询结果

[英]How to reformat/transform data query results before displaying them in DataGridView

I am using the DataGridView component to quickly and easily display read-only SQL query results to the user. 我正在使用DataGridView组件快速轻松地向用户显示只读SQL查询结果。 I have it working as desired, but I have to wonder if I'm doing things the "right" way. 我可以按需工作,但是我想知道我是否以“正确”的方式进行工作。 It's a complicated component after all, and I am completely new to SQL access and data binding in .NET. 毕竟,它是一个复杂的组件,我对.NET中的SQL访问和数据绑定是完全陌生的。

The MSDN help suggests using a BindingSource object as the intermediary, so I've come up with the following code (which seems to work just fine): MSDN帮助建议使用BindingSource对象作为中介,因此我想出了以下代码(似乎工作得很好):

mBindingSource.DataSource = null;
mBindingSource.Clear();

using (SqlDataReader query = GetQuery())
{
  if ((query != null) && (query.HasRows))
  {
    mBindingSource.DataSource = query;
    CDataGrid.DataSource = mBindingSource;
  }
}

However, I want to reformat some of this "raw" data. 但是,我想重新格式化一些“原始”数据。 For example, some of the values are stored as int or byte types in the underlying tables, but they actually represent various enum values. 例如,某些值存储为基础表中的intbyte类型,但它们实际上表示各种enum值。 Currently I am using the following code to perform the desired transformation (inspired by this MSDN page ): 当前,我正在使用以下代码执行所需的转换( 此MSDN页面启发):

private void CDataGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs args)
{
  DataGridViewColumn column = CDataGrid.Columns[args.ColumnIndex];
  switch (column.Name)
  {
    case FieldNameProductID:
    case FieldNameVersionID:
      int? x = args.Value as int?;
      ProductCode code = (ProductCode)(x ?? 0);
      args.Value = code.ToString();
      break;

    case FieldNameProductType:
      byte? y = args.Value as byte?;
      ProductType type = (ProductType)(y ?? 0);
      args.Value = type.ToString();
      break;
  }
}

Is this the proper way to do things? 这是做事的正确方法吗? The reason I ask is because it seemed as if the BindingSource object is designed partially to perform such types of transformations. 我问的原因是因为BindingSource对象似乎被设计为部分执行此类转换。 The documentation is hard to navigate, however, and I have yet to find a good example of what I'm trying to do. 该文档很难浏览,但是我还没有找到一个很好的例子来说明我要做什么。

This the correct way of doing it. 这是正确的方法。 The CellFormatting event captures the data before it is being rendered so it can be altered. CellFormatting事件会在呈现数据之前捕获数据,以便可以对其进行更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM