How do I find a control in a datalist?

N

needin4mation

I have this code:

protected void DataList1_ItemCreated(object sender,
DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType ==
ListItemType.AlternatingItem)
{
Label lbl = (Label)DataList1.FindControl("lblTest");
Response.Write(lbl.Text);
}
}

First, do I have to have that ListItemType.item, etc. stuff in asp.net
2.0? On the findcontrol, I did some searching and saw where I had to
have a something like

DataList1.FindControl(myID).FindControl("myControl");

I don't know what the myID is or if I need it.

Thank you for any help.
 
K

Karl Seguin [MVP]

Ya, you need to check for the Item || ItemType, since ItemCreated fires for
the headeritem and footeritem and the other templates, and you won't find
your control in there.

simply do:

e.Item.FindControl("lblTest");


e is the 2nd argument, e.Item is the DataListItem (which you can *think* of
as the actual row being bound)...within this row is the control you want to
find.

you CAN do it like DataList1.FindControl("XXX").FindControl("myControl");

but DataList1.FindControl("XXXX") just returns the same control as e.Item.

Karl
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top