简体   繁体   中英

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


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

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

I guess issue over here is UserCanEdit is not part your datasource for gridview. How can you Bind based on Property which is not part of your source. I guess what you are trying to do is you want to hide a column based on some user credential. Possible sulution would be user OnRowDataBound event. And inside that event user something like this

if(Condition)

((Label)e.Row.FindControl("C")).visible = true;

else

((Label)e.Row.FindControl("C")).visible = false;

Now you can set this codition inside actual Page_Load(Your web page) event.

Note: Condition is actully public property similar to your UserCanEdit

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