将xml根节点读入datagrid并将编辑内容写回xml文件

时间:2012-10-11 04:40:29

标签: c# xml

        this.dataGrid1 = new System.Windows.Forms.DataGrid();
        this.dataGrid1.DataMember = textBox1.Text.ToString();
        this.dataGrid1.Location = new System.Drawing.Point(36, 46);
        this.dataGrid1.Name = "dataGrid1";
        this.dataGrid1.Size = new System.Drawing.Size(364, 532);
        this.dataGrid1.TabIndex = 0;
        // 
        this.AutoScaleBaseSize = new System.Drawing.Size(50, 13);
        this.ClientSize = new System.Drawing.Size(592, 573);
        this.Controls.AddRange(new System.Windows.Forms.Control[] { this.dataGrid1 });
        ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
        this.ResumeLayout(false);


        XmlDataDocument xmlDatadoc = new XmlDataDocument();
        xmlDatadoc.DataSet.ReadXml("abcd.xml");

        DataSet ds = new DataSet("abc");
        ds = xmlDatadoc.DataSet;

        dataGrid1.DataSource = ds.DefaultViewManager; 

它显示了层次结构但它没有正确区分子节点和父节点。我只想看到应该是其子节点的链接的根节点。另外,我希望数据网格能够编辑xml文件。

2 个答案:

答案 0 :(得分:1)

将任何编辑内容写回xml文件,请使用以下命令:

DataSet ds= ((DataTable)datagrid1.dataSource).DataSet; 
//this statement populates the dataset.
//which is reflected in xml file as-- 
ds.WriteXml(s, XmlWriteMode.IgnoreSchema); 
ds.AcceptChanges();

答案 1 :(得分:0)

在DataSet中读取Xml后,为什么不将DataTable而不是整个DataSet设置为Grid的DataSource?

    XmlDataDocument xmlDatadoc = new XmlDataDocument();
    xmlDatadoc.DataSet.ReadXml("abcd.xml");

    DataSet ds = new DataSet("abc");
    ds = xmlDatadoc.DataSet;

    dataGrid1.DataSource = ds.Tables[0]; 

使用适当的根表调整表索引。