C# – Visible=’<%# UserCanEdit %>‘ – if set to true inside Page_Load, then control isn’t visible

asp.netcdata-bindinggridviewnet

User control defines a property named UserCanEdit:

private bool _userCanEdit=false;
public bool UserCanEdit
{
    get { return _userCanEdit; }
    set { _userCanEdit = value; }
}

This User Control also contains the following GridView:

    <asp:GridView ID="GridView1" runat="server">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Label ID="C" runat="server" Visible='<%# UserCanEdit %>' Text="Visibility"></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

For control C to be visible, UserCanEdit needs to be set to true. If I set it inside Page_Init(), then C is indeed visible. But if I set it inside Page_Load(), then C is not visible:

protected void Page_Load(object sender, EventArgs e)
{
    this.UserCanEdit = (this.Page.User.Identity.IsAuthenticated &&
       (this.Page.User.IsInRole("Administrators") ||
        this.Page.User.IsInRole("Editors")));

    GridView1.DataBind();
}

So why isn’t C visible if UserCanEdit is set inside Page_Load()? As far as I know, single-value binding expression <%#%> is evaluated only when GridView.DataBind() is called, which happens after UserCanEdit is set to true?!

cheers

Best Answer

My guess is because the controls are being defined before you have a value for UserCanEdit yet. Wouldn't the controls be loaded before the Page_Load() in the Page Initialization step?

http://msdn.microsoft.com/en-us/library/ms178472.aspx