我正在开发一个 Excel 2010 模板项目。在我的模板中,我有许多带有静态ListObject
控件的工作表。为了初始化 my ListObject
,我绑定 aBindingList<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>;
}
}
我一直在对此进行大量研究,但我无法找到解决方案,所以我希望你们中的一些人可以帮助我解决这个问题。
谢谢。