ClientID property of Dynamic CheckBox
Problem: I need to attach some javascript function for each of checkboxes with uniqueID inside Datalist.
When I’m trying to access ClientID inside OnItemCreated event in the code behind, it always resulting in the same ID which I’ve specified in design aspx page[It’s not generating the unique ID]. Note: While It results in proper Unique ID generation when I access in OnItemDataBound command. Any reasons why?
Following is the Code…
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
CheckBox chk = (CheckBox)e.Item.FindControl("chkUID");
if (chk != null)
{
chk.Attributes.Add("OnClick", "javascript:selectDiv(" + chk.ClientID.ToString() + ");");
}
}
}
Instead of building up everything in codebehind you should look into using the jQuery javascript library to attach the onclick event.
Often it’s much easier to do this on the client side with a jQuery select.
If your id’s start with chkUID you could do something like this:
For tutorials on jquery check out http://docs.jquery.com/Tutorials