简体   繁体   中英

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. 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.

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):

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. Currently I am using the following code to perform the desired transformation (inspired by this MSDN page ):

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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