【发布时间】:2011-12-29 11:50:41
【问题描述】:
我正在处理一个 Excel 2010 模板项目。在我的模板中,我有很多张带有静态ListObject 控件的表格。为了初始化我的ListObject,我绑定了一个BindingList<MyCustomType>,以便它为我的每个MyCustomType 公共属性生成一个列。这真的很方便,因为当用户在ListObject 中有一些行时,它会自动填满我的BindingList 实例。我在 Excel 功能区中添加了一个按钮,以便程序可以通过 EDM 验证和提交这些行。这就是我将数据绑定到我的一张 Excel 工作表的启动事件处理程序中的 ListObject 的方式。
public partial class MyCustomTypesSheet
{
private BindingList<MyCustomType> myCustomTypes;
private void OnStartup(object sender, System.EventArgs e)
{
ExcelTools.ListObject myCustomTypeTable = this.MyCustomTypeData;
BindingList<MyCustomType> customTypes = new BindingList<MyCustomType>();
myCustomTypeTable.SetDataBinding(customTypes);
}
// Implementation detail...
}
现在我的问题是该模板的用户很可能会在许多会话中输入这些行。这意味着他将输入数据,保存文件,关闭它,重新打开它,输入一些新行,并最终在他认为完成时尝试提交这些行。我注意到,当重新打开从模板创建的 Excel 文件时,我的 ListObject 控件的 DataSource 属性为空。这意味着我无法将ListObject 中的数据取回BindingList<MyCustomType>。我一直在搜索,我发现没有自动的方法来做到这一点,我真的不想制作一段代码来爬过所有的列来重新创建我的 MyCustomType 实例。在一个理想的世界里,我会这样做。
private void OnStartup(object sender, System.EventArgs e)
{
ExcelTools.ListObject myCustomTypeTable = this.MyCustomTypeData;
BindingList<MyCustomType> customTypes = null;
if (myCustomTypeTable.DataSource == null) // Will always be null and erase previous data.
{
customTypes = new BindingList<MyCustomType>();
myCustomTypeTable.SetDataBinding(customTypes);
}
else
{
customTypes = myCustomTypeTable.DataSource as BindingList<MyCustomType>;
}
}
我已经对此进行了大量研究,但我无法找到解决方案,所以我希望你们中的一些人可以帮助我解决这个问题。
谢谢。
【问题讨论】:
标签: excel data-binding vsto datasource listobject