How to find a control in a DataList?

November 30th, 2006 · 2 Comments

Reference: http://forums.asp.net/1072828/ShowPost.aspx

Because DataList is databound control which repeats its item template as many times as there are rows in the data source to it. Therefore contents of template are wrapped into DataList’s Items (one DataList item per row in data source) which is a naming container to its contents (to keep control ID naming scope unique with repeated controls)

You’d need to note that to locate a specific Label control, you’d first need to locate 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. instead of getting to one on specific row.

Iterating through all items in DataList

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″);
//…
}

No related posts.


Tags: Programming

2 responses so far ↓

  • 1 sepid // Sep 6, 2008 at 1:41 pm

    Hi,
    And Thanks for your article,

    could you please tell me what i should to do if i want to find control of especial row(choosed by clicking a button control)?
    is it possible you send me sample code?

  • 2 Waco // Sep 17, 2008 at 7:04 pm

    Hi sepid, please see my new post at http://www.wacofx.com/?p=400. Hope this help and please come back often and introduce your friends if you find my website useful. Thanks.

Leave a Comment

*
To prove you're a person (not a spam script), type the security text shown in the picture. Click here to regenerate some new text.
Click to hear an audio file of the anti-spam word

© 2006–2009 Now Eating — Sitemap