开发者

Easy way to set Enable=True or False based on a property

I have an <ItemTemplate> with an asp:LinkButton in, and I want to set the property Enabled to be true or false depending on a property I Eval(), something like this

    <asp:LinkButton ID="btnEdit" runat="server" Text="Edit" CommandName="Edit" 
Enabled='开发者_运维问答<%# (int?)Eval("KittenFriendlyStatus") == (int)KittenEnum.Awwwww %>' />

However my syntax is completely wrong, can anyone straighten it out for me, or suggest a better way of doing this? I've never done it with C# before, only Javascript.


You cannot use data-binding syntax on server-controls. To solve this problem, you need to find an event of the template control that happens when it binds. It will depend on the control. So, let's say the template control has a ItemDataBound event that passes the object beind bound. Add an event handler like this:

public void Control1_ItemDataBound(Control sender, Object data, EventArgs args) {
    sender.FindControl("btnEdit").Enabled = (int?)DataBinder.Eval(data, "KittenFriendlyStatus") == (int)KittenEnum.Awwwww;
}


should be like...

Enabled='<%# (int?)Eval("KittenFriendlyStatus") == (int)KittenEnum.Awwwww ? true : false %>'


In your instance, @Chiwee's suggestion of using the ItemDataBound event is likely what you need.

If you need to provide the ability to manage this in multiple places, you can use a property to manage things cleanly like this:

protected bool EnableEdit 
{
    get { return btnEdit.Enabled; }
    set { btnEdit.Enabled = value; }
}

or if you need to manage multiple buttons at once:

protected bool EnableEdit 
{
    set 
    {
        btn1.Enabled = value;
        btn2.Enabled = value;
        //...
    }
}


One way I use often is a function in code-behind to set property like:

Enabled=='<%# DoEnable(Eval("KittenFriendlyStatus"))%>' 

//in code-behind add this function:

public bool DoEnable(object status) 

{ 
   bool enable = //decide here 
   return enable; 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜