简体   繁体   English

使用WinForms在C#中从DataGridView保存数据

[英]Save data from DataGridView in C# with WinForms

I've two DataGridView one very simple and one more complex with different column types. 我有两个DataGridView,一个非常简单,另一个则具有不同的列类型。 My idea was to store store the data to XML and also load from the files at restart. 我的想法是将数据存储到XML并在重新启动时从文件加载。 For the simple one it's no problem (dgvAccounts is the DataGridView): 对于简单的一个来说,这没问题(dgvAccounts是DataGridView):

   DataTable dtusers = new DataTable("Users");
   DataColumn col1 = new DataColumn("ID");
   DataColumn col2 = new DataColumn("Key");
   dtUsers.Columns.Add(col1);
   dtUsers.Columns.Add(col2);
   if (File.Exists("user.xml"))
         dtUsers.ReadXml("user.xml");
   dgvAccounts.DataSource = dtUsers;     
   ....
   dtUsers.WriteXml("user.xml");  

But on the other DataGridView the DataTable I like to get from the DataSource is ever null (dgvActions is the DataGridView): 但是,在另一个DataGridView上,我想从DataSource中获取的DataTable永远为null(dgvActions是DataGridView):

   DataGridViewTextBoxColumn dgvcolA5 = new DataGridViewTextBoxColumn();
   DataGridViewComboBoxColumn dgvcolA6 = new DataGridViewComboBoxColumn();
   dgvActions.Columns.Add(dgvcolA5);
   dgvActions.Columns.Add(dgvcolA6);
   DataTable dtActions = (DataTable)dgvActions.DataSource;
   dtActions.WriteXML("actions.xml");

I'd also tried to create a DataTable in advance and add it as dgvActions.DataSource but the result is ever the same. 我还尝试过预先创建一个DataTable并将其添加为dgvActions.DataSource,但结果是一样的。

So please can somebody help me to create a DataTable for the DataGridView or suggest any other way to store and load the data? 因此,请有人可以帮助我为DataGridView创建一个DataTable或建议其他任何方式来存储和加载数据吗?

Thanks 谢谢

Andre 安德烈

What about setting up the datatable first and then setting it as the datasource like you do in the first example(then you wont get the null datatable from the datasource): 怎样像在第一个示例中那样首先设置数据表,然后将其设置为数据源(那么您将不会从数据源获取空数据表):

   DataTable dtActions = new DataTable();
   //Set DataTable columns here
   dtActions.WriteXML("actions.xml");
   dgvActions.DataSource = dtActions;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM