0

我的目標是通過按鈕單擊保存所有表單數據(而不是關閉時)。爲此,我使用了以下線程中給出的示例。 Saving the form state then opening it back up in the same state將表單狀態寫入xml C#

我試着將我的代碼調整到最佳狀態,但沒有任何反應,也沒有顯示錯誤。我究竟做錯了什麼?

這裏是我的代碼的相關部分:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.IO; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Xml.Serialization; 

namespace WindowsFormsApplication1 
{ 
    public partial class frmPayroll : Form 
    { 
     SaveData sd = new SaveData(); 
     public frmPayroll() 
     { 
      InitializeComponent(); 
     } 
private void saveToolStripMenuItem_Click(object sender, EventArgs e) 
     { 
      writeConfig(); 
     } 
     private void writeConfig() 
     { 
      using (StreamWriter sw = new StreamWriter("config.xml")) 
      { 
       sd.Married = rdoMarr.Checked; 
       sd.PayPd = cbPayPd.Text; 
       sd.Allow = cbAllow.Text; 
       sd.Gross = txtGross.Text; 
       sd.Fit = txtFit.Text; 
       sd.Soc = txtSoc.Text; 
       sd.Med = txtMed.Text; 
       sd.NetPay = txtNet.Text; 
       sd.PayPd = cbPayPd.Text; 
       XmlSerializer ser = new XmlSerializer(typeof(SaveData)); 
       ser.Serialize(sw, sd); 
      } 
     } 
     private void frmPayroll_Load(object sender, EventArgs e) 
     { 
      if (File.Exists("config.xml")) 
      { 
       loadConfig(); 
      } 
      sd.Married = rdoMarr.Checked; 
      sd.PayPd = cbPayPd.Text; 
      sd.Allow = cbAllow.Text; 
      sd.Gross = txtGross.Text; 
      sd.Fit = txtFit.Text; 
      sd.Soc = txtSoc.Text; 
      sd.Med = txtMed.Text; 
      sd.NetPay = txtNet.Text; 
     } 
     private void loadConfig() 
     { 
      XmlSerializer ser = new XmlSerializer(typeof(SaveData)); 
      using (FileStream fs = File.OpenRead("config.xml")) 
      { 
       sd = (SaveData)ser.Deserialize(fs); 
      } 
     } 
    } 
    public struct SaveData 
    { 
     public bool Married; 
     public string PayPd; 
     public string Allow; 
     public string Gross; 
     public string Fit; 
     public string Soc; 
     public string Med; 
     public string NetPay; 
    } 
} 

回答

0

你被反序列化加載你的對象。

但是你在哪裏將狀態分配回控件?

請看frmPayroll_Load功能。

您正嘗試將數據重新分配回對象。

您必須指定數據以形成控件。

應該是這樣的(你可能需要申請數據轉換如果需要的話):

rdoMarr.Checked = sd.Married; 
. 
. 
. 
. 
txtFit.Text = sd.Fit; 
. 
. 
. 
. 
+0

謝謝!它儘快嘗試。我拼命想弄清楚我做錯了什麼。我正在參加一個C#類,但沒有采取任何先決條件,所以有時難以理解MSDN上許多教程或示例所說的內容。現在嘗試添加一個清除按鈕。 – Gatorneck

+0

我試圖對您的答案進行投票,但我還沒有足夠的代表。 – Gatorneck

+0

你可以接受它作爲答案我猜....即使你不能upvote – Naidu