The ClientID property will return the ID of the control as it will eventually end up in the html source of the page.
Usually, the ClientID matches the ID of the control; e.g. a TextBox with an ID of txtTest will have an HTML attribute of txtTest.
However, controls nested in other controls, like a Repeater or DataGrid will have the ID of their container control as a prefix in their name, e.g. gridMyGrid__ctl3__txtTest for a TextBox control *inside* a DataGrid called gridMyGrid. This ensures that every HTML object has a unique ID throughout the enitre page (which is a requirement to use the control in JavaScript).
Consider the following example. At run-time I create a number of TextBoxes. In the example below I create only two, but I could just as easy create an unknown number of controls dynamically, in a loop for example. The controls are added to a PlaceHolder control.
Code:
TextBox txtBox1 = new TextBox();
TextBox txtBox2 = new TextBox();
txtBox1.ID = "txtBox1";
txtBox2.ID = "txtBox2";
PlaceHolder1.Controls.Add(txtBox1);
PlaceHolder1.Controls.Add(txtBox2);
RegisterArrayDeclaration("myArray",
String.Format("'{0}', '{1}'", txtBox1.ClientID, txtBox2.ClientID));
When the page has finished loading, you'll end up with the following JavaScript
:
Code:
<script language="javascript">
<!--
var myArray = new Array('txtBox1', 'txtBox2');
// -->
</script>
You can use this (dynamically generated) array inside a JavaScript function and do something with the controls. For example, you can see if they contain a value or not, as the following code demonstrates:
Code:
<script type="text/javascript">
function CheckControls()
{
for (var i = 0; i < myArray.length; i++)
{
if (document.getElementById(myArray[i]).value == '')
{
alert('Control ' + myArray[i] + ' cannot be empty');
}
}
}
</script>
This code uses the dynamic array and loops through it. Using the client side ID of the control as a parameter for the getElementById method, you can uniquely access each control in your page and with it whatever you see fit.
If you would add the controls to a repeated control, like a Repeater or DataGrid, you'll see that the ClientID of the control will return something different from its ID property, allowing you to uniquely identify the controls in the repeated items (e.g. TextBox1 for row 1 has a different ClientID than TextBox1 in row 2)
Of course this is a simple and rather limited example, but I am sure you can see the power of the RegisterArrayDeclaration method in combination with dynamic controls and client side JavaScript for validation and other purposes.
If you have any questions, feel free to ask.
Imar
---------------------------------------
Imar Spaanjaars
Everyone is unique, except for me.
While typing this post, I was listening to:
Hysteria by
Muse (Track 8 from the album:
Absolution)
What's This?