2015-02-24 57 views
-1

我試圖從datagridview中寫入,目標是將輸入保存到xml文件,但沒有正確地得到它。下面是我的代碼我如何從datagridview中寫入文件

  XDocument doc = XDocument.Load(outputFilePath); 
      doc.Save(outputFilePath); 
      oDataSet = new DataSet(); 

      foreach (DataGridViewRow _rows in Gridview_Output.Rows) 
      { 
       DataRow oDatarow = oDataTable.NewRow(); 
       for (int i = 0; i < Gridview_Output.ColumnCount; i++) 
       { 
        oDataTable.Rows.Add(oDatarow.ItemArray); 
       } 
      } 
      oDataSet.Tables.Add(oDataTable); 
      oDataSet.WriteXml(outputFilePath); 
      doc.Save(outputFilePath); 

我想寫這個空標籤

<data name="Exit_Button" xml:space="preserve"> 
<value></value> 
<comment>[Font][/Font][DateStamp][/DateStamp][Comment][/Comment]</comment> 
</data> 

回答

0

嗯試試這個從GridView的

private DataTable GetDataTableFromDGV(DataGridView dgv) { 

     var dt = new DataTable(); 
     foreach (DataGridViewColumn column in dgv.Columns) { 
      if (column.Visible) { 
       // You could potentially name the column based on the DGV column name (beware of dupes) 
       // or assign a type based on the data type of the data bound to this DGV column. 
       dt.Columns.Add(); 
      } 
     } 

     object[] cellValues = new object[dgv.Columns.Count]; 
     foreach (DataGridViewRow row in dgv.Rows) { 
      for (int i = 0; i < row.Cells.Count; i++) { 
       cellValues[i] = row.Cells[i].Value; 
      } 
      dt.Rows.Add(cellValues); 
     } 

     return dt; 
    } 

然後創建一個數據表,你可以做

DataTable dT = GetDataTableFromDGV(DataGridView1); 
      DataSet dS = new DataSet(); 
      dS.Tables.Add(dT); 
      dS.WriteXml(File.OpenWrite("xml.xml")); 
+0

來自評論部分,請給我一個例子e喜歡編碼作爲例子,那麼我會改變它,以滿足我的需求 – 2015-02-24 15:02:36

+0

你是什麼意思,通過編碼作爲例子?這是編碼 – user2726374 2015-02-24 15:06:33

+0

我如何能夠根據DGV命名該列? – 2015-02-24 15:08:06