tags:

views:

37

answers:

3

I have a datalist and in its header template I have a linkbutton.In my codebehind file I wrote as I've always written:

((LinkButton)(DataList1.FindControl("LinkButton1"))).Enabled = false;

but this gives me the error:

Object reference not set to an instance of an object.

How can I access this linkbutton?

+1  A: 

Your call to FindControl isn't finding anything - you need to ensure that something is found before you cast it and try to use it.

This approach is safer:

LinkButton linkButton 
    = DataList1.FindControl("LinkButton1") as LinkButton;

if (linkButton != null)
    linkButton.Enabled = false;
Andrew Hare
ok I did and linkButton is null but my LinkButton1 is there. What should I do?
erasmus
+1  A: 

If the LinkButton is embedded in a container like a Panel or other control you will have to reach inside of it. FindControl does not recurse through the child controls of the collection.

For example, you might have to do something like this with whatever nested control structure you have:

FindControl("Panel1").FindControl("LinkButton1").Enabled ...
John K
+1  A: 

You should use FindControl() in the template that you use (e.g ItemTemplate)

Halo