【问题标题】:Button not enabling after it is disabled按钮禁用后无法启用
【发布时间】:2017-09-04 13:31:06
【问题描述】:

我有一个包含人名的项目列表。我已经做到了,一旦到达列表的末尾,按钮就会被禁用,因此很明显没有更多的项目了。问题是当我返回上一个项目时,即使我重新启用了该按钮,该按钮仍然处于禁用状态...

所以我有禁用/启用按钮的方法,并且在 button_click 事件处理程序中有对该方法的调用:

public void DisableButton()
{
    if(birthdays.IsThereAnotherItem())
    {
        btnNext.Enabled = true;
    }
    else if (!birthdays.IsThereAnotherItem())
    {
        btnNext.Enabled = false;
    }           
}

我还激活了 button_EnabledChanged 事件处理程序。

我像这样回到上一个项目......

private void btnPrevious_Click(object sender, EventArgs e)
{
    birthdays.StepToPreviousPerson();
    DisplayPeople();      
}

【问题讨论】:

  • 为什么不btnNext.Enabled = birthdays.IsThereAnotherItem(); 并删除所有ifs?
  • 你如何“回到上一个项目”?你应该在这个函数/方法中也包含这个方法
  • @DmitryBychenko 相同的结果...(按钮在列表末尾禁用但不会再次启用)。
  • @MongZhu 更新了我的帖子
  • 您使用 DisableButton() 来禁用和启用按钮 - 混淆命名。无论如何,您确定当用户单击“上一个”按钮时正在调用此函数吗?我在您发布的代码中没有看到。

标签: c# winforms list controls


【解决方案1】:

何时必须检查是否禁用 btnNext 按钮? birthday所选项目已更改btnNext 当且仅当最后一个项目被选中时才应该被禁用。

假设birthdayListBoxSelectionModeSelectionMode.One 你可以这样说:

   private void birthday_SelectedIndexChanged(object sender, EventArgs e) {
     // Previous is Enabled if and only if the selected item is not first one
     btnPrevious.Enabled = birthday.SelectedIndex > 0; 

     // btnNext is enabled if and only if
     //   1. birthday has items (not empty)
     //   2. An item selected
     //   3. The item is not the last one 
     btnNext.Enabled = birthday.SelectedIndex >= 0 && // an item selected
                       birthday.SelectedIndex < birthday.Items.Count - 1;
   }

因此,每当birthday 选择发生更改时,您都会同时更新btnNextbtnPrevious(无论出于何种原因 - StepToPreviousPersonStepToNextPerson 调用、直接选择等)

【讨论】:

  • 在选择“下一个”或“上一个”按钮时检查是否禁用按钮(对不起,我没有在这里显示它们)。 'birthday' 不是一个列表框,它只是一个文本框。
【解决方案2】:

好的,我是根据@Eli 的评论知道的。我必须将 DisableButton() 的函数调用放在我已经拥有的“btnPrevious”事件处理程序以及“Next”按钮事件处理程序中。非常简单的事情,我从一开始就错过了。

感谢所有提供帮助的人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    • 2013-03-29
    • 2010-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多