Sunday, July 6, 2014

ASP.net ReadOnly TextBox get value on PostBack

Level: Intermediate

Knowledge Required:
  • ASP.net
  • Custom Controls

In ASP.net we have a problem, that if we set a TextBox control ReadOnly, then the value changed through JavaScript cannot be received back to Server on PostBack.

If we search on Google, we will find that a good solutions is to add readonly attribute on the Page_Load. For example,

protected void Page_Load(object sender, EventArgs e)
{
     TextBox1.Attributes.Add("readonly", "readonly");
}

So putting this code for every control and on every page is obviously a bit annoying. So a better way is to create your own TextBox control which implements this behaviour. But since we already have a good TextBox control available so we can just extend it

    public class ExtendedTextBox : System.Web.UI.WebControls.TextBox
    {
        public override bool ReadOnly
        {
            get
            {
                // We will always return ReadOnly false because internally control
                // is checking this property and it will start the same behaviour
                // if we return true, i.e. value will NOT be received on PostBack 
                return false;
            }
            set
            {
                // Here I have implemented a logic, if we you mark the control as
                // readonly then we will render it as background-color = light gray
                if (value)
                {
                    this.Attributes.Add("readonly", "readonly");
                    this.BackColor = System.Drawing.Color.WhiteSmoke;
                }
                else
                {
                    this.Attributes.Remove("readonly");
                    this.BackColor = System.Drawing.Color.White;
                }
            }
        }
    }

The point is, actually we do NOT set the ReadOnly property of control to true, just add the readonly attribute, so that ASP.net control will consider itself as normally rendered control, and will return the value correctly.

After this we can easily use this control on any web page, but before this we have to add the control reference in our web.config file as,

  <system.web>
    <pages>
      <controls>
        <add assembly="YourWebApplicationAssemblyName" namespace="NameSpaceWhereYouHaveThisExtendedClass" tagPrefix="asp"/>
      </controls>
    </pages>
  </system.web>