문제

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

도움이 되었습니까?

해결책

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"] = ...

다른 팁

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; 
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top