Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Common issues to ASP.NET input controls for Enabled / Visible / ReadOnly Properties

0.00/5 (No votes)
13 Dec 2009 1  
Hi Guys,It is common behavior of ASP.NET that if a control is set to Visible = false, the response stream doesn't contain the definition of it. Therefore, if you want to make the control visible during runtime from Javascript always put display = none in styles attribute.Say you have a...
Hi Guys,

It is common behavior of ASP.NET that if a control is set to Visible = "false", the response stream doesn't contain the definition of it. Therefore, if you want to make the control visible during runtime from Javascript always put display = none in styles attribute.

Say you have a textbox which you want to make invisible but want to display when required from the browser.

<asp:textbox id="txt" runat="server" />

In codebehind instead of writing
txt.Visible=false;

You write:
txt.Style.Add(HtmlTextWriterStyle.Display, "none");

If you take the 2nd approach, the server will render the control and send to the client and finally will not be displayed because of display:none CSS style. You may again show the control using the following javascript :

var elem = document.getElementById("txt"); 
elem.style.display='block';


Note : It is better to use txt.ClientID instead of txt directly as identifier in Javascript.


Another issue of ASP.NET is with setting Enabled = false / Readonly=true.

In case of Enabled=false or Readonly = true, ASP.NET sends the input control to the browser, but any changes made in the control in client side will not reflect in the server.
That means, whenever the control is recreated in the web server during postback, it will not include the Form data posted for the control. Thus the initial value will be restored.

Therefore, to overcome the issue again, you should put
ctrl.Attributes.Add("readonly", "readonly");
ctrl.Attributes.Add("disabled", "disabled");


This will work the same way but the value changes in the client side will reflect to the server side controls.

So if you want to work with the controls in the client side using javascript, dont use restriction using properties from server side, rather use CSS Attributes to do this.

Hope you will like this. :rose:

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here