2012-05-01 23:59:39|?次阅读|上传:wustguangh【已有?条评论】发表评论
如果dataSource是IListSource类型的实例,则调用InitDataSet方法对DataSourceManager类的数据进行初始化,InitDataSet方法的定义如下:
private void InitDataSet() {
Columns = new ArrayList();
Rows = new ArrayList();
DataTable table = ((DataSet)dataSource).Tables[this.dataMember];
// use reflection to discover all properties of the object
foreach (DataColumn c in table.Columns)
Columns.Add(c.ColumnName);
foreach (DataRow r in table.Rows) {
DataSourceRow row = new DataSourceRow(this, r);
for (int i = 0; i < Columns.Count; i++)
row.Add(r[i]);
Rows.Add(row);
}
}
该方法比较容易理解,首先将dataSource强制转换成DataSet类型,然后从中获取对应表名为dataMember的DataTable数据表,根据该数据表的内容实例化DataSourceManager类的数据成员。
b. InitList
如果dataSource是IList类型的实例,则调用InitList方法对DataSourceManager类的数据进行初始化,InitList方法的定义如下:
private void InitList() {
Columns = new ArrayList();
Rows = new ArrayList();
IList list = (IList)dataSource;
// use reflection to discover all properties of the object
BindingFlags bf = BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty;
PropertyInfo[] props = list[0].GetType().GetProperties();
foreach (PropertyInfo pi in props)
Columns.Add(pi.Name);
foreach (object obj in list) {
DataSourceRow row = new DataSourceRow(this, obj);
foreach (PropertyInfo pi in props) {
object result = obj.GetType().InvokeMember(pi.Name, bf, null, obj, null);
row.Add(result);
}
Rows.Add(row);
}
}
该方法默认传入的IList类型实例dataSource是一个对象的链表,使用C#反射的特性获取链表中对象的公共属性名称以及对应的值,构成列标题和行数据内容,最后逐行加入到Rows属性中。
c. InitGrid
如果dataSource是OutlookGrid类型的实例,则调用InitGrid方法对DataSourceManager类的数据进行初始化,InitGrid方法的定义如下:
private void InitGrid() {
Columns = new ArrayList();
Rows = new ArrayList();
OutlookGrid grid = (OutlookGrid)dataSource;
// use reflection to discover all properties of the object
foreach (DataGridViewColumn c in grid.Columns)
Columns.Add(c.Name);
foreach (OutlookGridRow r in grid.Rows) {
if (!r.IsGroupRow && !r.IsNewRow) {
DataSourceRow row = new DataSourceRow(this, r);
for (int i = 0; i < Columns.Count; i++)
row.Add(r.Cells[i].Value);
Rows.Add(row);
}
}
}
由于dataSource已经是一个OutlookGrid类型的实例,所以其数据的列模型和行数据与当前的类型一致,只需要简单的复制过来即可。
到此,自定义的DataGridView类型网格组件的设计工作介绍完成了,下面通过客户端程序介绍自定义DataGridView控件的使用方法。新建一个Windows窗体应用程序,将其命名为OutlookGridApp,并将其添加到当前解决方案中。
将刚才创建的OutlookGrid组件拖动到Form1中,如图:
