Search code examples
c#asp.netviewstateobject-persistence

Persisting a control's properties


OK Time for another dumb Q from yours truly.

I have a control that has some properties that need to be persisted in the ViewState. I also need to make sure that the properties aren't overwritten if the control appears more than once on the page.

I thought to write something like...

ViewState[String.Format("{0}_{1}", "BaseKey", this.ClientID)] = ...

But the value of ClientID changes partway through the page's lifecycle. It starts out as something like "MyControl1" and then becomes "ctl001_MyControl1". So any values applied before it changes are lost.

The same thing happens if I use UniqueID instead.

I know I'm missing something obvious, and I'm going to blame the pills I'm taking so I don't look too dumb.

-- Stuart


Solution

  • it looks like you are doing this inside the user control, if that is true you do not need to make a unique key for the viewstate, each instance of every control manages it's own viewstate so all you need is a key known to your control, something like that:

    ViewState[@"somekey"] = ...