darma teja

darma teja

  • NA
  • 496
  • 329.8k

object reference not set to an instance of anobjectException

Sep 4 2014 4:49 PM
Hi All,

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);
            test.Show();
        }

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

Answers (2)