tags:

views:

121

answers:

4

Hi,

In ASP>Net using C#, I declared a variable as member of the class as follows:

public class sales: System.Web.UI.Page
{
string type=null;
}

And i have an Image Button in my UI for which I've defined the event called

protected void ImageButton2_Click(object sender, ImageClickEventArgs e)

in this method, any value assigned to variable 'type'(by any other method of the class) is not retained and only value null is being retrieved though I've assigned some value to 'type' somewhere inside the class...

What could be the problem that I cant access the assigned value????

+3  A: 

You have to persist data between postbacks.

I recommend you to read these articles:

CMS
A: 

This is probably a result of the render pipeline. Remember, even though your event is being fired, the page and all variables are recreated with their default value. Create it as a property with at least a backing viewstate storage.

public String Type 
{
    get { return ViewState["Type"].ToString(); } 
    set { ViewState["Type"] = value; } 
}
Joshua Belden
A: 

Each time you do a request to the page, the variable is re-initialized, if it is a postback or not.

Try to put your variable in a property instead of a field (as you are doing) and initialize the propertie the first time you load the page, only if is not a postback.

You should do something like:

  //on the On_Load page's event
  if (!IsPostback)
    Type = null;    

  private string Type { get; set; }
eKek0
A: 

If your assigning the value in your object and then doing a postback with the button, the value will be gone unless you stored that instance of the object in the session, viewstate, or something.

string sType = "something";
Session["YourSessionTagHere"] = sType;

Once the postback occurs you can then fetch the object out and access the value from your onclick event.

string sType = (string)(Session["YourSessionTagHere"]);

It just sounds like your not accessing the same object and your object is getting lost because after each postback your string would be new.

You could also make this a bit cleaner by just setting up a property that does the session stuff for you in the get and set.

Kelsey