我一直在嘗試讀取xml並將其打印在datagrid中,然後再次單擊save時將其寫回到同一個文件中,以便如果在某個時間後打開它,我可以使用新的文件。所以,這是我做的:MDIForms:WriteXml:空引用異常
DataSet ds;
private void Form2_Load(object sender, EventArgs e)
{
cmd = new SqlCommand("getCustomers", conn);
cmd.CommandType = CommandType.StoredProcedure;
da = new SqlDataAdapter(cmd);
ds = new DataSet();
//da.Fill(ds, "Productslist");
ds.ReadXml(@"C:\Users\Nishanth\documents\visual studio
2010\Projects\Ex1\Ex2\ShoppingCart1.ds");
dataGridView1.DataSource = ds.Tables[0];
}
所以,這裏我從xml中讀取併爲它分配一個網格。在接下來的幾行中,當我點擊父級mdi表單上的保存按鈕並調用子表單的writeX方法時,我寫了一個事件。
public void writeX()
{
MessageBox.Show("I'm in writeX()");
ds.WriteXml(@"C:\Users\Nishanth\documents\visual studio
2010\Projects\Ex1\Ex2\ShoppingCart1.ds");
}
這裏,在步中WriteXML,我得到和錯誤說
Null Reference Exception : Object reference not set to an instance of an object.
父窗體代碼
private void customer_clicked(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.MdiParent = this;
f2.MaximizeBox = true;
f2.Show();
}
private void products_clicked(object sender, EventArgs e)
{
Form1 f = new Form1();
f.MdiParent = this;
f.MaximizeBox = true;
f.Show();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.writeX();
}
因此,可以ü請讓我知道這個錯誤我一直在做?
更新了代碼 – user838359
可以讓我知道如何處理這個問題嗎? – user838359
我實例化全局數據集。然後在form2_load中更新ds,然後編寫xml,它不寫任何內容(清除所有內容;猜測ds爲null)。 – user838359