Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net

I have a FindControl in OnLoad event to find my button on page i.e.:

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.


1 Answers

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.

like image 80
Canavar Avatar answered May 19 '26 09:05

Canavar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!