ClientID is a way that ASP.NET uses to generate unique element IDs when an items is repeated in controls like GridView, DataList or Repeater controls. The ClientID can be used in the client-side Javascript to access the element. However, I found that when I tried to access the ClientID in the Item_Created event, the ClientID will not be unique. If I try to access the ClientID in the Item_Databound event instead, the ClientID is unique. The following code snippet shows the behavior:
<%@ Import Namespace="System.Data" %>
<html>
<head>
<script language="C#" runat="server">
ICollection CreateDataSource() {
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
dt.Columns.Add(new DataColumn("DateTimeValue", typeof(DateTime)));
for (int i = 0; i < 9; i++) {
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Item " + i.ToString();
dr[2] = DateTime.Now;
dt.Rows.Add(dr);
}
DataView dv = new DataView(dt);
return dv;
}
void Page_Load(Object Sender, EventArgs e) {
if (!IsPostBack)
BindList();
}
void BindList() {
DataList1.DataSource= CreateDataSource();
DataList1.DataBind();
}
void DataList_ItemCommand(object Sender, DataListCommandEventArgs e) {
string cmd = ((LinkButton)e.CommandSource).CommandName;
if (cmd == "select")
DataList1.SelectedIndex = e.Item.ItemIndex;
BindList();
}
protected void DataList1_ItemCreated(object sender, DataListItemEventArgs e)
{
//If you do it here, clientID will not be unique
//Control c = e.Item.FindControl("button1");
//string clientID = c.ClientID;
}
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
//If you do it here, clientID will be unique
Control c = e.Item.FindControl("button1");
string clientID = c.ClientID;
}
</script>
</head>
<body>
<h3><font face="Verdana">Using a SelectedItemTemplate with DataList</font></h3>
<form id="Form1" runat=server>
<font face="Verdana" size="-1">
<asp:DataList id="DataList1" runat="server"
BorderColor="black"
BorderWidth="1"
GridLines="Both"
CellPadding="3"
Font-Names="Verdana"
Font-Size="8pt"
Width="150px"
HeaderStyle-BackColor="#aaaadd"
AlternatingItemStyle-BackColor="Gainsboro"
SelectedItemStyle-BackColor="yellow" OnItemCreated="DataList1_ItemCreated" OnItemDataBound="DataList1_ItemDataBound"
>
<ItemTemplate>
<asp:LinkButton id="button1" runat="server" Text="Show details" CommandName="select" />
<%# DataBinder.Eval(Container.DataItem, "StringValue") %>
</ItemTemplate>
</asp:DataList>
</font>
</form>
</body>
</html>