Pages

Monday, October 31, 2011

How to find a control in a DataList?


How to find a control in a DataList?

Because DataList is databound control which repeats its item template as many times as there are rows in the data source. Therefore contents of
So, to locate a specific Label control, you’d first need to locate a specific dataList item, and run FindControl to it (for example DataList1.Items(0).FindControl(“label2″) ), and considering the databound nature, you’d probably want to loop through all items in the DataList’s Items collection to get to the every Label control.

VB
For Each dli as DataListItem in DataList1.Items
Dim currLbl As Label=DirectCast(dli.FindControl(“label2″),Label)
    '…
Next


C#
foreach(DataListItem dli in DataList1.Items)
{
Label currLbl = (Label) dli.FindControl(“label2″);
//…

}