Saturday, March 24, 2012

Maintaining state in Custom Controls

Hi I have more of the same components in my aspx page. These .ascx contain one Date.ascx to pick dates. I am trying to maintain state in these Date.ascx with viewstate.

But I am getting error
(Object reference not set to an instance of an object.)
when inserting the

return (DateTime)ViewState["Pdtdate_2"];

On the other hand
return (DateTime)ViewState["Pdtdate_1"];

works fine.

private DateTime pdtdate_1;
public DateTime Pdtdate_1
{
get {return (DateTime)ViewState["Pdtdate_1"]; }
set { ViewState["Pdtdate_1"] =value; }
}
private DateTime pdtdate_2;
public DateTime Pdtdate_2
{
get {return (DateTime)ViewState["Pdtdate_2"]; }
set { ViewState["Pdtdate_2"] =value; }
}

Please help. Rek

When using get, you should make sure that the object in the viewstate isn't null, if it is, return a default value. If you are using C# 2.0, you can have nullable value types.
I am using C# 2.0. So that shouldnt be the case.

But How Come This works fine:

private DateTime pdtdate_1;
public DateTime Pdtdate_1
{
get
{return (DateTime)ViewState["Pdtdate_1"]; }
set
{ ViewState["Pdtdate_1"] =value; }
}

AND this doesnt?

private DateTime pdtdate_2;
public DateTime Pdtdate_2
{
get
{return (DateTime)ViewState["Pdtdate_2"]; }
set
{ ViewState["Pdtdate_2"] =value; }
}


I have reviewed my script but none of these work what is the problem.
Why don't you debug your app and set a break point on the get of both properties and check for the values of both viewstate variables. It looks like one of them works because you had previously set the value and the other is still null.
None of them works I was wrong!!! what can I do? please easy answers I new to asp.net

We've alrady gave you a couple of solutions to what you can do. You have to post more info on what's going on. Did you debug? What have you found?

Sometimes the problem is on the logic.

0 comments:

Post a Comment