0

我有一个下拉菜单

 <div>
     <asp:DropDownList ID="RegistrationDropDownList" runat="server">
         <asp:ListItem Value="NULL">All records</asp:ListItem>
         <asp:ListItem Value="1">Submitted records</asp:ListItem>
         <asp:ListItem Value="0">Non-Submitted records</asp:ListItem>
     </asp:DropDownList>
 </div>

我想<asp:ListItem Value="NULL">All records</asp:ListItem>根据会话变量显示/隐藏

所以我这样尝试

 <asp:DropDownList ID="RegistrationDropDownList" runat="server">
 <%if (Convert.ToInt32(Session["user_level"]) == 1){ %>
     <asp:ListItem Value="NULL">All records</asp:ListItem>
 <%}%>
     <asp:ListItem Value="1">Submitted records</asp:ListItem>
     <asp:ListItem Value="0">Non-Submitted records</asp:ListItem>
 </asp:DropDownList>

但我有一个错误

在此上下文中不支持代码块

我知道我不能在具有 runat="server" 的控件上使用代码块,但删除它会破坏我的逻辑代码。

我怎么解决这个问题 ?

4

3 回答 3

3

这应该在后面的代码中完成:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack && Convert.ToInt32(Session["user_level"]) == 1)
    {
        RegistrationDropDownList.Items.Insert(0, new ListItem("All records", "NULL"));
    }
}
于 2013-07-18T17:35:09.747 回答
0

ListItem没有Visibility可以绑定的属性是一种耻辱。我能想到的最佳解决方案是编写一个扩展类DropDownList;添加一个在渲染之前插入“所有记录”项的方法。

public class ExtendedList : DropDownList
{
    protected override void OnLoad(EventArgs e)
    {
        if (Convert.ToInt32(Session["user_level"]) == 1)
        {
            Items.Insert(0, new ListItem { Value = "NULL", Text = "All Records" });
        }
    }
}
于 2013-07-18T17:33:46.113 回答
0

在后面的代码中添加

if (Convert.ToInt32(Session["user_level"]) == 1)
            {
                ListItem newItem = new ListItem();
                newItem.Value = null;
                newItem.Text = "All record";
                DropDownList1.Items.Add(newItem);

            }
于 2013-07-18T17:37:56.400 回答