我是 c# 的初学者,我创建了一个dataGridView1
in a Form
我添加了一些行和列(不使用DataSet
and Datatable
)。现在我需要发送数据dataGridView1
到一个 xml 文件。 xml 文件应该update每当我点击那个按钮时。我需要在不使用的情况下执行此操作Datatable
(或表格)。我尝试了下面的代码(不工作)
单击按钮
XmlTextWriter newXml = new XmlTextWriter("d:/newXML.xml", Encoding.UTF8);
DataSet ds = new DataSet(dataGridView1.Rows.ToString()); /* May be I am missing something here */
ds.WriteXml(newXml);
xml 文件创建成功但显示<System.Windows.Forms.DataGridViewRowCollection />
in it.
如果我添加BindingSource bs = (BindingSource)dataGridView1.DataSource;
before DataSet
,它显示错误“对象引用未设置到对象的实例。”
Note:如果 xml 文件不是他们的,那么它应该创建一个。
提前致谢。
你可以实例化一个DataTable
并从你的dataGridView1
控制:
DataTable table = new DataTable("Customers");
// copy the correct structure from datagridview to the table
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
table.Columns.Add(column.Name, typeof(string));
}
// populate the datatable from datagridview
for (int rowIndex = 0; rowIndex < dataGridView1.Rows.Count; rowIndex++)
{
table.Rows.Add();
for (int columnIndex = 0; columnIndex < dataGridView1.Columns.Count; columnIndex++)
{
table.Rows[rowIndex][columnIndex] = dataGridView1[rowIndex, columnIndex].Value;
}
}
然后继续其余代码:
DataSet ds = new DataSet();
ds.Tables.Add(table);
ds.WriteXml("d:/newXML.xml", System.Data.XmlWriteMode.IgnoreSchema);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)