2
我正在使用DataGridView
組件來快速方便地向用戶顯示只讀SQL查詢結果。我希望它能夠正常工作,但是我不得不懷疑我是否以「正確」的方式做事。畢竟它是一個複雜的組件,而我完全不熟悉.NET中的SQL訪問和數據綁定。如何在將數據查詢結果顯示在DataGridView中之前重新格式化/轉換數據查詢結果
MSDN幫助建議使用BindingSource
對象作爲中介,所以我想出了下面的代碼(這似乎只是正常工作):
mBindingSource.DataSource = null;
mBindingSource.Clear();
using (SqlDataReader query = GetQuery())
{
if ((query != null) && (query.HasRows))
{
mBindingSource.DataSource = query;
CDataGrid.DataSource = mBindingSource;
}
}
不過,我想重新格式化一些這個「原始」數據。例如,某些值在底層表中存儲爲int
或byte
類型,但它們實際上代表各種enum
值。目前我使用下面的代碼來執行所需的轉換(由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;
}
}
這是做事情的正確方法?我問的原因是因爲看起來好象BindingSource
對象被設計爲部分執行這種類型的轉換。文檔很難瀏覽,但是,我還沒有找到我想要做的一個很好的例子。