0
votes

I have inherited textbox and dropdownlist controls in C# and added some custom logic to them for setting background and all in C# I am adding them to my user control(ascx) and using this usercontrol in aspx page. But On postback I lose values for all textboxes dropdown etc. Can anyone help.

1
If you are dding the controls from code you need to add them in OnInit every time the page loads. - Magnus
No I am not adding them from code behind I have added them directly in ascx by adding registering namespace tag - gayatri Kadam
You are going to have to show us how you are doing it. - Magnus
<%@ Register TagPrefix="WebControls" Assembly="Controls" Namespace="My.WebControls" %> - gayatri Kadam
Check ViewState on parent control. - Xaqron

1 Answers

2
votes

That's just the way it works, and it's worse than you think. It's not that your control is losing it's data. It's that it's not even same instance of the control any more.

In ASP.Net, you work with a completely new instance of your page class, including any controls in the class, on every postback. There is a page lifecycle you need to understand before you'll be able to do much, but the summary goes like this:

  1. User sends an http request for a page via the browser
  2. ASP.Net runtime in IIS creates an instance of the page and calls methods like Pre_Init, Load, Render, etc in a specific order.
  3. The result of this process is then used to send an http response to the user's browser with the rendered html.
  4. Once the response is sent, the page class instance is disposed and destroyed. It no longer exists.
  5. The browser receives the http response and renders the page for the user.

If the user does anything that causes a postback, the entire process starts again. It's a whole new http request, a whole new page class, and a whole new http response. Things like calling the page's Load method are repeated. Also note the order for steps 4 and 5. Due to latency between the browser and web server, it's common that the page class is already destroyed before the response even reaches the user. By the time the user sees a page, the class instance that produced the page is already long gone.

To get around this, you need to put data that should persist across requests into a storage location that will actually persist, such as ViewState or the Session.