Another Object reference not set to an instance of an object
-
Code in page_load is if (!IsPostBack) { Label x = new Label(); x.ID="lblQuestionX"; x.Text="Robert"; plhQuestions.Controls.Add(x); } pressing submit button private void Button1_Click(object sender, System.EventArgs e) { if (Page.IsValid) { Label lblTemp = new Label(); lblTemp = (Label)plhQuestions.FindControl("lblQuestionX"); string strNumber = lblTemp.Text; last line generates error: Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. What stupid thing am I doing wrong this time? cheers Robert T Turner South Gloucestershire Council
-
Code in page_load is if (!IsPostBack) { Label x = new Label(); x.ID="lblQuestionX"; x.Text="Robert"; plhQuestions.Controls.Add(x); } pressing submit button private void Button1_Click(object sender, System.EventArgs e) { if (Page.IsValid) { Label lblTemp = new Label(); lblTemp = (Label)plhQuestions.FindControl("lblQuestionX"); string strNumber = lblTemp.Text; last line generates error: Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. What stupid thing am I doing wrong this time? cheers Robert T Turner South Gloucestershire Council
Robert, The problem is that you dont re-create the Label on postback. Remember the page no longer exists internally when the page is sent to the client, on postback, ASP.NET recreates the page (object) and 'sets' values defined in the viewstate. So in your example when Button1_Click is executed, "lblQuestionX" no longer exists. To correct the problem, try the following in your Page_Load:
Label x = new Label();
x.ID = "lblQuestionX";
plhQuestions.Controls.Add(x);if (!IsPostBack)
{
// only set the initial value when delivering fresh page
x.Text = "Robert";
}Also, in your OnClick handler you don't need to create an instance of Label. FindControl will return you a reference to the object. Hope this helps, Andy
-
Robert, The problem is that you dont re-create the Label on postback. Remember the page no longer exists internally when the page is sent to the client, on postback, ASP.NET recreates the page (object) and 'sets' values defined in the viewstate. So in your example when Button1_Click is executed, "lblQuestionX" no longer exists. To correct the problem, try the following in your Page_Load:
Label x = new Label();
x.ID = "lblQuestionX";
plhQuestions.Controls.Add(x);if (!IsPostBack)
{
// only set the initial value when delivering fresh page
x.Text = "Robert";
}Also, in your OnClick handler you don't need to create an instance of Label. FindControl will return you a reference to the object. Hope this helps, Andy
Thanks very much. I knew it would be something stupid. I very new to .net and I flitting back and from between asp and asp.net. You help is very much appreciated Robert T Turner South Gloucestershire Council