在使用asp.net 2.0 beta 2 開發項目的過程中,碰到了將對象數組綁定到GridView的數據源上,但是使用排序的時候,卻發現GridView並不提供對對象數組的支持,而在微軟的官方網站上我們可以看到GridView的排序只有當數據源是DataSet的時候才支持,所以對於某些採用了O/R映射的項目或者返回的數據源是對象數組的項目中,就需要考慮提供將對象數組轉換爲DataSet的方法了,否則就要自己來手工來實現每一個GridView的排序,降低了開發效率。
在微軟的.net開發類庫中,我們找不到現成轉換方法,所以就需要考慮自行開發這個功能了,然而實現起來並不是很複雜,其中要用到的主要技術就是反射。利用反射,我們能夠獲取該對象數組中對象的每一個屬性,包括其名稱、類型,然後利用這些信息來創建DataSet中數據表的Schema,當創建完成以後,將該對象數組的每一個對象的屬性數據複製到剛纔創建的數據表中,這樣就很簡單的完成了該功能的實現,還是用代碼來說的更清楚些:
文件:objectArrayToDataSet.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Reflection;
public class ArrayToDataSet
{
public static DataSet ObjectArrayToDataSet(object[] objArr)
{
if (objArr.Length == 0)
return null;
DataSet ds = CreateDataSet(objArr[0].GetType());
ds = FillDataSet(ds, objArr);
return ds;
}
public static DataSet CreateDataSet(Type t)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
ds.Tables.Add(dt);
PropertyInfo[] pis = t.GetProperties();
foreach (PropertyInfo pi in pis)
{
DataColumn dc = new DataColumn(pi.Name, pi.PropertyType);
dt.Columns.Add(dc);
}
return ds;
}
public static DataSet FillDataSet(DataSet ds, object[] objArr)
{
DataColumnCollection dcs = ds.Tables[0].Columns;
Type t = objArr[0].GetType();
foreach (object obj in objArr)
{
DataRow dr = ds.Tables[0].NewRow();
for (int i = 0; i < dcs.Count; i++)
{
dr[i] = t.InvokeMember(dcs[i].ColumnName, BindingFlags.GetProperty, null, obj, null);
}
ds.Tables[0].Rows.Add(dr);
}
return ds;
}
}