加入状态为true或false时启用或禁用按钮

时间:2014-03-06 22:16:27

标签: c# asp.net

我希望当我的表中的“join status”行为true时启用按钮“Button_Join”,当它为false时禁用该按钮。

代码:

<asp:Repeater ID="RepeaterTeam" runat="server">
 <ItemTemplate>
  <tr>
   <td>
     <asp:Button ID="Button_Join" runat="server" Text="Join" Enabled='<%#Enabled() %>'/>
   </td>
  </tr>
 </ItemTemplate>
</asp:Repeater>

代码背后:

protected bool Enabled()
{

    if (Session["join status"] == "False")
    {
        return false;
    }
    else
    {
        return true;
    }
}

我不知道怎么做,但这是我的猜测,但它似乎不起作用。

这可能代替所有这些代码吗?

<asp:Button ID="Button_Join" runat="server" Text="Join" Enabled='<%#Eval ("join status") %>'/>

4 个答案:

答案 0 :(得分:0)

在后面的代码中设置启用控制。

 protected void Page_Load(object sender, EventArgs e)
 {
     this.Button_Join.Enabled = Session["join status"] != "False";
 }

更新

为您的转发器添加OnItemDataBound的处理程序

<asp:Repeater runat="server" ID="myRepeater" OnItemDataBound="myRepeater_ItemDataBound">

protected void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    Button button = (Button)e.Item.FindControl("Button_Join");
    button.Enabled = Session["join status"] != "False";
}

最好把会话bool改成字符串。你可以这样使用它

button.Enabled = (Session["join status"] as bool?) ?? false;

答案 1 :(得分:0)

为什么不在按钮的加载事件中执行此操作?

protected void Button_Join_Load(object sender, EventArgs e)
{
   // your logic...
   (sender as Button).Enabled = false;
}

编辑:

如果根据您的评论按钮位于转发器中,请使用转发器的ItemDataBound事件:

protected void Your_Repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    RepeaterItem ri = e.Item;
    var btn = (ri.FindControl("Button_Join") as Button);
    if (btn != null) btn.Enabled = 
        bool.Parse((Session["join status"] ?? false).ToString()) == true ? true : false;
}

答案 2 :(得分:0)

我猜你可能不得不使用Enabled='<%=Enabled() %>'代替Enabled='<%#Enabled() %>'

<%# %>用于数据绑定。我看到你没有绑定任何数据。 <%= %>相当于Response.Write()

更多信息here ...

答案 3 :(得分:0)

使用启用功能

尝试此操作
Enabled='<%#Eval("Enabled")%>'