Persisting a control's properties
-
25-10-2019 - |
Question
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"] = ...
OTHER TIPS
Try doing it on Page_PreRender rather than Page_Load?
Don't store the value named relative to the output name of the control itself. Provide it with a unique, unchanging name and then make sure all of your binding rules adjust to that name instead of the client name.
Edit:
As a small example of what I mean:
MyControl ctrl1 = new MyControl();
ctrl1.ID = "MyControlA";
ctrl1.Text = "Some text";
ViewState[ctrl1.ID] = ctrl1.Text;
MyControl ctrl2 = new MyControl();
ctrl2.ID = "MyControlB";
ctrl2.Text = "Some other text";
ViewState[ctrl2.ID] = ctrl2.Text;