Property in a Windows Forms form class only accessable after Load event
I'm instantiating and calling Form B from Form A. FormB has some custom properties, to allow me to pass it things like sqlAdaptors and dataset instances.
When i instantiate and show Form B from Form A as a dialog form with a Using statement, it all works fine, but i find the properties i pass are not available in Form B until after the form_load event has fired.
I was under the impression the properties when passed to a instantiated class should be availab开发者_JAVA百科le from a constructor, but this is not the case. If it try to access the properties before the form load event i get a null reference exception.
Is this correct behavior ?
Move all the Form B internal variable initialization to its constructor
Here is how your formA will look like. It has 2 buttons: One simply initializes an instance of formb and call the public property. The other button displays formB. Form_load is only called when you show the form to the user via Show() or ShowDialog() calls.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace formload
{
public partial class FormA : Form
{
public FormA()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FormB frm = new FormB();
MessageBox.Show(frm.MyProperty);
frm = null;
}
private void button2_Click(object sender, EventArgs e)
{
FormB frm = new FormB();
frm.ShowDialog();
MessageBox.Show(frm.MyProperty);
frm = null;
}
}
}
Here is how formb would look:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace formload
{
public partial class FormB : Form
{
public FormB()
{
InitializeComponent();
myPropString = "Default set via constructor";
}
private void FormB_Load(object sender, EventArgs e)
{
myPropString = "Set from form load";
}
private string myPropString;
public string MyProperty
{
get { return myPropString; }
set { myPropString = value; }
}
}
}
If you're doing
FormB frm = new FormB(); ' Constructor runs now
frm.MyProperty = "whatever"; ' Now you set the property
frm.ShowDialog()
Obviously, you're running the constructor before you set the property! You can't access the property until after you set it.
精彩评论