【问题标题】:Import/Export DataGridView with format C#以 C# 格式导入/导出 DataGridView
【发布时间】:2015-08-15 23:42:04
【问题描述】:

我在 Visual Studio 的界面生成器中创建了一个 DataGridView。 DataGridView 具有三列,其中一列包含复选框。 当应用程序启动时,datagridview 应该是空的(除了标题)。这就是 DataGridView 目前没有DataSource 的原因。我正在尝试将其导出为 XML 文件,以便下次打开应用程序时可以导入此文件。

我尝试了很多方法来导出和导入我的 DataGridView,但没有一种方法能正常工作。是否有适当的方法来导入和导出数据网格视图并保持格式?

将 DataGridView 保存为 XML 以外的其他格式也可以,但由于应用程序必须在多台计算机上运行,​​这些计算机都会在服务器上创建许多文件,因此文件大小应该很小。

【问题讨论】:

标签: c# winforms datagridview import export


【解决方案1】:

正如rlee 指出的那样,ReadXmlWriteXml 应该可以工作。我放在一起的最基本的原始示例与单元格中的复选框配合得很好。

public partial class Form1 : Form
{
  private DataTable table;

  public Form1()
  {
    this.InitializeComponent();

    this.table = new DataTable("Table");
    DataColumn col1 = new DataColumn("Check", typeof(bool));
    DataColumn col2 = new DataColumn("Text", typeof(string));
    this.table.Columns.Add(col1);
    this.table.Columns.Add(col2);

    this.table.ReadXml("test.xml");
    this.dataGridView1.DataSource = this.table;
  }

  private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  {
    this.table.WriteXml("test.xml");
  }
}

然后在.exe文件所在的位置保存一个名为test.xml的xml文件:

<?xml version="1.0" standalone="yes"?>
<DocumentElement>
  <Table>
    <Check>true</Check>
    <Text>Row 0</Text>
  </Table>
  <Table>
    <Check>false</Check>
    <Text>Row 1</Text>
  </Table>
</DocumentElement>

【讨论】:

    【解决方案2】:

    您可以将网格绑定到数据表,并使用datatable.ReadXml("filename.xml")datatable.WriteXml("filename.xml")

    【讨论】:

    • 谢谢。我已经尝试过了,但是将网格绑定到数据表会导致在单元格中使用复选框时出现问题。
    • +1 来自我,它工作得很好。 @ Maarten1909 我在回答中提供了一个示例,它是如何工作的。如果仍然没有帮助,您遇到了什么问题?
    猜你喜欢
    • 2010-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-28
    • 2019-01-03
    • 1970-01-01
    相关资源
    最近更新 更多