使用基类对象列表时,使DataGridView显示派生类对象的属性

时间:2013-07-11 02:45:18

标签: c# list data-binding datagridview .net-3.5

如果成员被保存在基类类型的列表中,其中的属性不存在,有没有办法让DataGridView显示我的派生类的属性?说我有以下内容:

public class MyBaseClass
{
public int MyPropertyBase { get; set; }
//...
}

public class MyDerivedClass : MyBaseClass
{
public int MyPropertyDerived { get; set; }
//...
}

// Create list of type MyBaseClass, holding MyDerivedClass objects
List<MyBaseClass> list = new List<MyBaseClass>();
list.Add(new MyDerivedClass(1));
list.Add(new MyDerivedClass(2));
list.Add(new MyDerivedClass(3));

// Declare DataGridView
DataGridView dataGridView = new DataGridView();
dataGridView.AutoGenerateColumns = false;

// Create display column for DataGridView
DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();

当我将列表绑定到DataGridView并显示MyPropertyBase属性时,它可以正常工作:

// Select MyPropertyBase to display in column
col.DataPropertyName = "MyPropertyBase";
dataGridView.Columns.Add(col);
dataGridView.DataSource = list;

但是,如果我希望使用相同的MyPropertyDerived显示List<MyBaseClass>,它将无效并且只显示空单元格(尽管它显示了与列表中的项目对应的单元格数) :

// Select MyPropertyDerived to display in column
col.DataPropertyName = "MyPropertyDerived";
dataGridView.Columns.Add(col);    
dataGridView.DataSource = list;

我真的需要将这个列表保存到我的抽象基类中,因为它在代码的其他地方使用。有没有办法将派生类属性公开给DataGridView(如果它们存在),如果属性不存在则只显示并清空单元格?真正有用的是让每个派生类公开(通过属性)绑定到DataGridView时要显示的所有内容,并让DataGridView从列表中填充。

2 个答案:

答案 0 :(得分:2)

一种方法是回退列表中的每个元素,进行下一次更改,然后在datagridview中获得1,2,3:

col.DataPropertyName = "MyPropertyDerived";
dataGridView.Columns.Add(col);
dataGridView.DataSource = list.ConvertAll(c => c as MyDerivedClass);

答案 1 :(得分:1)

如果您实现ITypedList并修改方法GetItemProperties的返回,则可以绕过数据绑定CurrencyManager的限制