views:

245

answers:

2

hi

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

+2  A: 

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

Mark
Here's a follow up article to Mark's suggestionhttp://www.15seconds.com/issue/020102.htm
Nick
I understand page's lifecycle. Controls indeed are initialized prior to Page_Load(), but that doesn't mean you can't change control's properties after they are initialized ( thus inside Page_Load() ).
SourceC
+1  A: 

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

Neil