如何datagridview的行添加到XML文件? [英] How to add datagridview rows to an xml file?
问题描述
我在C#初学者,我创建了一个 dataGridView1
在表格
来,我增加了一些行列(的不使用的DataSet
和数据表
的)。现在我需要 dataGridView1
的数据发送到一个XML文件中。 XML文件应的更新每当我点击该按钮。我需要做到这一点,而无需使用数据表
(或表)。我想下面的代码(不工作的)
I am a beginner in c#, I created one dataGridView1
in a Form
to which I added some rows and columns (without using DataSet
and Datatable
). Now I need to send the data of dataGridView1
to an xml file. The xml file should update whenever I click on that button. I need to do this without using Datatable
(or tables). I tried the below code (not working)
OnButtonClick
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 /方式>
它
如果我想补充的BindingSource BS =(的BindingSource)dataGridView1.DataSource;
的DataSet
之前,它显示错误对象引用不设置到对象的实例。
If I add BindingSource bs = (BindingSource)dataGridView1.DataSource;
before DataSet
, it is showing error "Object reference not set to an instance of an object."
注意:如果XML文件是不是他们的话,应该创建一个提前
Note: If the xml file is not their then it should create one.
感谢
推荐答案
您可以实例化一个数据表
并从 dataGridView1 <填充它/ code>控件:
You can instantiate a DataTable
and populate it from your dataGridView1
control:
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;
}
}
然后继续你的代码的其余部分:
then continue with the rest of your code:
DataSet ds = new DataSet();
ds.Tables.Add(table);
ds.WriteXml("d:/newXML.xml", System.Data.XmlWriteMode.IgnoreSchema);
这篇关于如何datagridview的行添加到XML文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!