Thursday, September 17, 2009

Q) What's Wrong in this? Getting "NullReferenceObject Exception"

C#:
I have getting "System.NullReferenceException: Object refernce not set to an instance of an object, at" .
This Exception is getting when giving the some text into the textbox's & Clicking Button of Windows Control Library form (usercontrol) which is placed the UC_submitcontrol usercontrol on the UCTestApp1 Windows Form and Execute.

See the Pictures:



Code for UC_SubmitControl1:
namespace UC_SubmitControl1
{
public partial class UC_SubmitScreen : UserControl
{
public delegate void SubmitClickHandler();
public event SubmitClickHandler SubmitbtnClicked;

public UC_SubmitScreen()
{
InitializeComponent();
}

private void btnSubmit_Click(object sender, EventArgs e)
{
if(tbText.Text.Length==0)
MessageBox.Show("Please Enter Some Text..!");
else
{
OnSubmitClicked();
}
}

protected virtual void OnSubmitClicked()
{
if (SubmitbtnClicked != null)
{
SubmitbtnClicked(); // Notify Subscribers
}
}

public string Prop_TextHere
{
get { return tbText.Text; }
set { tbText.Text = value; }
}
}
}


See the Picture for UC_TestApp1 [Windows Application]


Code for UC_TestApp1:
namespace UC_TestApp1
{
public partial class Form1 : Form
{
private UC_SubmitControl1.UC_SubmitScreen submitscrObj;
//private System.ComponentModel.Container components = null;


public Form1()
{
InitializeComponent();
}

private void uC_SubmitScreen1_SubmitbtnClicked()
{
try
{
MessageBox.Show(String.Format("Hello, {0}!", submitscrObj.Prop_TextHere));
//string aa = submitscrObj.Prop_TextHere;
//MessageBox.Show("Hello ", +aa.ToString()+" !");
//this.Close();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
this.Close();
}
}
}
}

2 comments:

  1. You're trying to use the object before it was instantiated, instantiate it like this.

    Code Snippet

    1. public Form1()
    2. {
    3. InitializeComponent();
    4. submitscrObj = new UC_SubmitControl1.UC_SubmitScreen();
    5. }

    ReplyDelete
  2. Hello!,
    You have 2 UC_SubmitControls. The one you are trying to use is the one that is not initialized to anything. Rather remove the private submitscrObj and use the designer created one.
    The one that is shown on the screen is the one that the designer created. This one should have a name of UC_SubmitScreen1 if you have not change the default name. Look at the name in the designer.

    change the line

    MessageBox.Show(String.Format("Hello, {0}!", submitscrObj.Prop_TextHere)) ;

    to read

    MessageBox.Show(String.Format("Hello, {0}!", uC_SubmitScreen1.Prop_TextHere));

    ReplyDelete

Followers