2009-02-27 89 views
1

請幫我將DataGrid導出爲XML。 我嘗試了兩種方法,但都導致拋出異常。將Datagrid導出爲xml

DataTable dt = (DataTable)dataGrid2.DataSource; 
dt.WriteXml("t.xml", XmlWriteMode.IgnoreSchema); 

該投用消息一個InvalidOperationException「無法序列的數據表。數據表名稱未設置。」

請推薦一種合適的方法將數據網格導出爲XML。

+0

新增更新再評論 – 2009-02-27 07:27:04

回答

1

Here's a link以Marc的建議爲例。

向下滾動到示例的SerializeToXML和DeserializeFromXML方法。

0

鑑於該錯誤;只需設置DataTable的名稱?

dt.TableName = "Fred"; 
... 

就個人而言,我會使用對象序列化(或許XmlSerializer超過List<T>),但DataTable應該沒事......


更新;例如使用DataTable.WriteXml/ReadXml;注意「這條線使它工作」評論;這是必要的a:能夠寫入,b:正確讀取行。

using System; 
using System.Data; 
static class Program 
{ 
    static void Main() 
    { 
     DataTable table = CreateEmptyTable(); 
     table.Rows.Add(1, "abc"); 
     table.Rows.Add(2, "def"); 
     WriteTable(table); 
     table.WriteXml("t.xml", XmlWriteMode.IgnoreSchema); 

     DataTable clone = CreateEmptyTable();   
     clone.ReadXml("t.xml"); 
     WriteTable(clone); 
    } 
    static DataTable CreateEmptyTable() 
    { 
     DataTable table = new DataTable(); 
     table.Columns.Add("Foo", typeof(int)); 
     table.Columns.Add("Bar", typeof(string)); 
     table.TableName = "MyTable"; // THIS LINE MAKES IT ALL WORK 
     return table; 
    } 
    static void WriteTable(DataTable table) { 
     foreach (DataColumn col in table.Columns) 
     { 
      Console.Write(col.ColumnName); 
      Console.Write('\t'); 
     } 
     Console.WriteLine(); 
     foreach (DataRow row in table.Rows) 
     { 
      foreach (DataColumn col in table.Columns) 
      { 
       Console.Write(row[col]); 
       Console.Write('\t'); 
      } 
      Console.WriteLine(); 
     } 
    } 
} 
+0

這是行不通的再次相同的錯誤 如何序列u能詳細解釋 – Arunachalam 2009-02-27 04:51:15

0

這個答案是特定於C#中的winforms,但一般應用於ASP.NET編程。下面,_dtResults是一個全局數據表。早些時候,當您將DataGrid(dg)源綁定到DataTable時,只需將副本放入全局變量_dtResults即可。然後致電ExportXMLFromDG()

// user clicks on button, which binds the dg to the datatable, 
    // prompts the user to save the XML, serializes it and saves the file. 
    private void toolStripButton4_Click(object sender, EventArgs e) 
    { 
     dg.DataSource = dtResults; // this actually happens earlier. 
     _dtResults = dtResults; // this actually happens earlier. 

     if (dg.Columns.Count > 0) 
     { 
      SaveFileDialog saveFileDialog1 = new SaveFileDialog(); 

      saveFileDialog1.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*"; 
      saveFileDialog1.FilterIndex = 1; 
      saveFileDialog1.RestoreDirectory = true; 

      if (saveFileDialog1.ShowDialog() == DialogResult.OK) 
      { 
       ExportXMLFromDG(saveFileDialog1.FileName); 
      } 
     } 
    } 


    private void ExportXMLFromDG(string xml_file) 
    { 
     XmlSerializer serializer = new XmlSerializer(typeof(DataTable)); 
     TextWriter textWriter = new StreamWriter(xml_file); 
     serializer.Serialize(textWriter, _dtResults); 
     textWriter.Close(); 

    }