The ID Property is Important

I’ve encountered quite a few developers having ViewState problems with dynamic controls. Ever have a control get recreated, but the value isn’t there on PostBack and you are creating your controls at the correct time? Frustrating to say the least. Anyway, even if you follow the correct pattern for creating / recreating dynamic controls, you may either forget (D’oh) or don’t set (Double D’oh) an ID for the control. By not setting an ID, you are relying on ASP.NET to create the control with the same ID. Sometimes it will, other times it won’t… not a gamble you should take.

Recently, I ran into a problem with this. For some reason, I simply forgot to set the ID for one of my controls. I had sporadic results and couldn’t figure out why. Sometimes one of the controls would have the value, and other times I came up completely empty. It’s amazing how blind one can be when reviewing their own code :). Anyway, setting an ID made all my issues go away, and I felt pretty stupid.

Enabled and ReadOnly Fun

One other thing to note on this topic that I encountered. I was creating a standard ASP.NET TextBox dynamically, pretty easy. My requirement was to restrict the user from changing the value. Just to get the full picture of the problem, I was also using a Wizard control to allow previous and next actions. I needed to maintain the ViewState for these dynamic controls since the user could go back and in the Finish Step I needed to read this value in order to save everything. Anyway, back to the requirement. Ok, the user shouldn’t be able to edit the value, let’s set it to Enabled = false. Great, run it, no ViewState. After a bit of research, you’ll find that this isn’t a .NET problem, it has to do with the client-side disabled property. When a control is marked as “disabled”, it isn’t persisted when the form is posted, therefore, ASP.NET is not aware of it when the ViewState gets loaded. So the next logical step was ReadOnly with a bit of style to make it “look” disabled. However, if you look at the spec for ReadOnly, you will find an important note roughly half way down the page that states the server does no processing on a ReadOnly TextBox. Since I’m creating the controls dynamically, this equates to no ViewState for me again. What a pain. In the end, the solution was to just add the client-side attribute readonly to the TextBox, like so…

TextBox1.Attributes.Add("readonly", "readonly");

And again, I added a simple CSS style to make it look disabled:

.disabled { background-color:#ddd; color:#666; }