2016-11-09 23 views
-1

我有這樣的代碼C#中加入XML問題

private void submitButton_Click(object sender, EventArgs e) 
    { 
     XDocument doc = XDocument.Load("order.xml"); 
     XElement root = new XElement("MenuInfo"); 

     foreach(DataGridViewRow dr in dataGridView.Rows) 
     { 
      if(dr.Selected) 
      { 
       root.Add(new XElement("Meal", dr.Cells["Food"].Value.ToString())); 
       root.Add(new XElement("SeatID", _seat)); 
       root.Add(new XElement("TableID", buttonTable1.Text)); 
       root.Add(new XElement("Price", dr.Cells["Price"].Value.ToString())); 
       doc.Element("Menu").Add(root); 
       doc.Save("order.xml"); 
      } 
     }  

     MessageBox.Show("The order has been placed."); 
     Main nf = new Main(); 
     nf.ShowDialog(); 
     this.Close(); 
    } 

它用於工作,我會用下面的元素和值創建一個order.xml文件,但現在沒有任何反應。它仍然會提示消息框說明訂單已放置,但是當我查看xml文件時,沒有添加任何內容。任何人都可以向我解釋爲什麼發生這種情況?

+1

是博士選?你的數據網格中有行嗎?這些是我可以看到會阻止創建xml文件的唯一兩個原因。 –

+1

好吧,也許'dataGridView.Rows'爲空,或'dr.Selected'總是'false',或者沒有'doc.Element(「Menu」)',或者'doc.Save'失敗。你有沒有試過一次一行代碼? –

+0

@JohnnyMopp我已經解決了,謝謝你的幫助 –

回答

0

正如其他人所建議的,數據網格可能爲空。我會以submitButton_Click功能添加驗證這樣

if (dataGridView.Rows.Count == 0) 
{ 
    "throw some error" 
} 

如果你過去是那麼我也將檢查的XDocument,以確保有內容。包裝你的代碼以顯示另一個if語句中的對話框。像這樣的東西

if(doc.ToString().Length > 0) 
{ 
    "Your dialog code here" 
}