Handling Dynamic Control Names in Asp.Net

This blog explains how we can replace the dynamic control ids with the static once.

Many times we come across code where the developer has used dynamic control names. For example:

  1. document.getElementById('_ctl8_Attachment').value = textBoxVal;  
This causes lot of javascript errors when the web page is actually up and running.

Cause: The control name changes dynamically at runtime and so the required element is not found by the browser.

Solution

Set the ClientID mode when creating the control.
  1. <asp:TextBox ID="Attachment" runat="server" ClientIDMode="Static" ></asp:TextBox>  
Now you can simply search for the control with its actual ID:
  1. document.getElementById('Attachment').value = textBoxVal;