I’ve been trying to read xml and print it in datagrid and then again on clicking save write it back to the same file so that if i open it after sometime, i can have the new files. So, this is what I did:
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];
}
So,here i read from xml and assign it a grid. In the next few lines i write an event when I click save button on the parent mdi form and call the child form’s writeX method.
public void writeX()
{
MessageBox.Show("I'm in writeX()");
ds.WriteXml(@"C:\Users\Nishanth\documents\visual studio
2010\Projects\Ex1\Ex2\ShoppingCart1.ds");
}
here, at WriteXml step, I get and error saying
Null Reference Exception : Object reference not set to an instance of an object.
Parent form code
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();
}
So, can u please let me know the mistake i’ve been doing?
At the time you’re calling
writeX,dshas not been instantiated. With the code provided, it’s impossible to tell why that’s the case.It’s most likely you have two
ds‘s declared in different scopes.EDIT: Given the updated example shows that it’s not an issue of
ds‘s scope, the next thing to look for is the lifetime of theForm2object. It’s a likely two different instances are in use when NullReferenceException occurs. That is, a second instance was likely created but never shown, the Load event never firing, anddsnever getting instantiated.EDIT: It’s obvious now. You’re not using the same
Form2insaveToolStripMenuItem_Clickas you are incustomer_clicked.You’ll need a class-level
Form2instance.