简体   繁体   中英

FindControl doesn't work with bind server tag, why?

I have a FindControl in OnLoad event to find my button on page ie:

protected override void OnLoad(EventArgs e)
{
    DataBind();
    control button = Page.FindControl("myButton");
}

on my aspx page I have

<asp:Button runat="server" ID="myButton" />

If I only have this, everything works, when I pass in the OnLoad, button is not null and I can execute what I want. The problem is when I add dynamic text in my aspx:

<asp:Button runat="server" ID="myButton" Text='<%# "Here is my dynamic text pulled from a XML" %>' />

Then the FindControl finds nothing and the button is null.

Adding a binding server tag on aspx isn't suppose to delay anything right? When I inspect the Page object I have some controls in Controls collection, but I'm unable to find myButton.

Any idea on what I am doing wrong?

EDIT

People seem to think that my code example is my real code but it isn't , So I use FindControl because I need to since I have nested controls and I cannot access it directly and I use binding because the dynamic text I'm putting is inside a ContentTemplate which I can override in other page aspx.

The question I asked was more specific to the fact that I have traced the problem where my FindControl returns null because a newly implement behaviour which is the binding.

Improving the code example isn't a solution or an explanation to the fact that if I put a <%# %> tag in my aspx page, the FindControl in the OnLoad event return null.

EDIT 2

the bind tag alone seems to not be the culprit but the DataBind() to populate them. Whether or not I have bind tag, putting DataBind() before the FindControl makes the myButton to be null. Correction in code example was made.

The Page.FindControl() method will only search the imediate collection of controls that are associated with Page. It will not recurse down the entire control tree, so if your button is contained within another control it will not be found. You would need to call the FindControl method on the containing control.

In here MSDN says that :

PreRender : Each data bound control whose DataSourceID property is set calls its DataBind method.

It looks like you're not using DataSourceID of your data bound control, but moving your FindControl code to PreRender event might help.

If you want to access a button on your page, you can directly refer to the button as -

this.myButton

And as far as assigning values is concerned, you can do it like this in your server code -

this.myButton.Text = "Dynamic Text";

<%# xyz %> is only used when you are databinding the controls, for eg in a DataGrid, GridView, etc.

在您的覆盖中,您不想首先在您的方法中调用 base.OnLoad(e) 吗?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM