I am getting the exception "object reference not set to an instance of an object Exception".
I wrote logic in buttion1 click event in "Form1"
private void button1_Click(object sender, EventArgs e)
{
Form2 test = new Form2(richTextBox1.Text);
Form2 test = new Form2(richTextBox1.Text);
test.Show();
}
I wrote following logic in Form2:
I am getting the following exception:
System.NullReferenceException was unhandled
when I use InitializeComponent(); in public Form2(string p) {} constructor, It is working fine. Please explain me why it happens?
Advance thanks, Darma
I wrote following logic in Form2:
namespace Form1
{
public partial class Form2 : Form
{
private string p;
public Form2()
{
InitializeComponent();
}
public Form2(string p)
{
this.p = p;
using (StringReader reader = new StringReader(p))
{
string line;
while ((line = reader.ReadLine()) != null)
{
listBox1.Items.Add(line);
}
}
}
}
}
I am getting the following exception:
System.NullReferenceException was unhandled
when I use InitializeComponent(); in public Form2(string p) {} constructor, It is working fine. Please explain me why it happens?
Advance thanks, Darma
VulpesPosted Sep 4, 2014, 5:22 PM
It's written to by the VS designer and you shouldn't normally meddle with it yourself. If you do, your changes are likely to be overridden.
When you create a WF application in VS all your form constructors should call the InitializeComponent method otherwise you're certain to get a null reference exception when the form attempts to access a control. As an alternative to including it explicitly, you can also use constructor chaining:
public Form2 (string p) : this()
{
// blah
}
darma tejaPosted Sep 5, 2014, 4:52 AM