【问题标题】:Disabling asp button when no items selected in list box在列表框中未选择任何项目时禁用 asp 按钮
【发布时间】:2016-02-21 18:47:51
【问题描述】:

如果在列表框中未选择任何项目,我希望禁用我的按钮。我将按钮启用设置为 false。选择项目时,按钮确实启用true,但是,在启用按钮后,当没有选择列表项时,它不会禁用。

后面的代码:

protected void Button2_Click(object sender, EventArgs e)
{
    List<ListItem> itemsRemove = new List<ListItem>();

    foreach (ListItem listItem in ListBox1.Items)
    {
        if (listItem.Selected)
            itemsRemove.Add(listItem);

    }

    foreach (ListItem listItem in itemsRemove)
    {
        ListBox1.Items.Remove(listItem);
    }


}

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    foreach (ListItem item in ListBox1.Items)
    {
        if (item.Selected)
        {
            Button2.Enabled = true;
        }
    }
}

【问题讨论】:

    标签: c# asp.net webforms


    【解决方案1】:

    试试这个:

    protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Button2.Enabled = false;
    
        foreach (ListItem item in ListBox1.Items)
        {
            if (item.Selected)
            {
                Button2.Enabled = true;
            }
        }
    }
    

    但这不是此类功能的最佳解决方案,最好使用一些 javascript 代码来启用/禁用您的按钮。

    编辑(最小解决方案):

    protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Button2.Enabled = ListBox1.Items.Any(x => x.Selected);
    
    }
    

    【讨论】:

    • 感谢您的快速回复和建议。不幸的是,这并没有纠正问题。删除所选项目后,该按钮仍处于启用状态。
    • Button2.Enabled = false; 移动到 Page_Load 或在按钮单击处理程序中调用 ListBox1_SelectedIndexChanged 方法
    【解决方案2】:

    您还应该将ListBoxAutoPostBack 属性设置为true,并且按钮和ListBoxEnableViewState 必须设置为true

    【讨论】:

    • 请将您的答案移至评论,或编辑现有答案
    猜你喜欢
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    相关资源
    最近更新 更多