saadan
saadan

Reputation: 487

findcontrol problems

why can not I do this

I have a data list which retrieves some data out. if the label1 is we say 123 then a second label2 must be invisible

    Label Label1 = (Label)DataList2.FindControl("LabelName1");
    Label Label2 = (Label)DataList2.FindControl("LabelName2");

    if (Label1.Text == "123")
    {
        Label2.Visible = false;
    }

when it coms to
if (Label1.Text == "123")
it says Object reference not set to an instance of an object.

Upvotes: 0

Views: 1546

Answers (4)

John Leidegren
John Leidegren

Reputation: 61037

It depends on where in the page life-cycle you are. The DataList uses ASP.NET templates to build it's internal control collection, this doesn't happen until you've called DataBind, which normally happens automatically just before PreRender. And you can't find controls in the control collection until they have been created.

Where in the page life-cycle are you doing this? What's the context? There's other things to which can further complicate this (one thing is that FindControl is not recursive) in that it will not necessarily search down through each and every naming container. But I'd like to know more about in what context this doesn't work, becuase it does, but you need to be careful.

EDIT:

Something like this should do the trick:

<asp:DataList runat="server" ID="DataList1" OnPreRender="DataList1_PreRender">...</asp:DataList>

And then code behind:

protected void DataList1_PreRender(object sender, EventArgs e)
{
    // the sender in this case is the DataList1 control
    // i often prefer to rely on the sender argument
    Label label1 = (Label)((Control)sender).FindControl("Label1");
    label1.Text = "Yay, it looks like this works!";
}

Upvotes: 1

dretzlaff17
dretzlaff17

Reputation: 1719

I would check to ensure that "LabelName2" exists. You may have a typo.

Upvotes: 0

Vishal
Vishal

Reputation: 12369

EDIT : Also mention what you cannot do and what error you get to get a better answer... You dont want to use 'Label'(since Label is a keyword/class) as the name of the first one..name it Label1 or something...and use String.Compare() to compare strings...

Upvotes: 0

VoodooChild
VoodooChild

Reputation: 9784

You forgot to mention what you can't do? what is happening with the it is now?

Also is it "LabelName" or "LabelName1" like you mentioned in the comment - those can be confuling 'l' and '1' (hard to spot)

Upvotes: 0

Related Questions