Well, this has been under discussion for sometime and I knew this was a known issue although it was a design change in ASP.NET 2.0.
I am talking about the TextBox which has the Read Only property assigned true not retaining the values or client side changes getting ignored across postbacks. There are certain blogs / articles which talk about it but for the benefit of those who get stuck with this, I am giving herebelow the steps to reproduce and the resolution for the same.
Try doing this
Declare a TextBox
<asp:TextBox ID=”TextBox1″ runat=”server” Text=”Sample Text” ReadOnly=”true” />
Add the following Button
<asp:Button ID=”Button1″ runat=”Server” Text=”Submit” OnClick=”Button1_Click” />
The purpose of the above button is to invoke a code behind method, the click event where we can do a Response.Write of the TextBox value.
So, in the code behind, add the following method
protected void Button1_Click(object sender, EventArgs e)
then add the following button
<input type=”Button” name=”Button2″ onclick=”changevalue()” />
The client side script is as follows:-
this.form1.TextBox1.value = “Modified Sample Text”;
Place the above script before the </head> tag in your HTML Source.
Now, if you click on the input type button you will see that the TextBox value changes to “Modified Sample Text“.
However, when you click on the button “Submit” which is an <asp:Button>, a server control, you will see that the text that it writes to the browser is again “Sample Text“. You will also see that the TextBox has the value reset to “Sample Text”.
This behaviour is new in ASP.NET 2.0 and if you are migrating your ASP.NET 1.x applications you may find this a little annoying / worrying since the values aren’t retained.
This is independent of whether you set the EnableViewState property for the TextBox to true or false. In fact the EnableViewState property for a TextBox doesnt make a difference since the values in a TextBox are maintained and retrieved from the Form’s Collection and not from the ViewState.
However, there is a work around for the same. Instead of setting the “Read Only=true” property in the design you can enable the ReadOnly property of the TextBox through the Attributes collection in the code behind. To do that, remove the ReadOnly property from the TextBox declaration above. Then, in the code behind file, within the Page_Load add the following line of code:-
This behaviour is by design in ASP.NET 2.0 and it has been designed with the idea that a ReadOnly TextBox shouldnt be modified in the client side by a malicious code.