简体   繁体   中英

Q: C# - How To Enable / Disable Button According To If ListboxItem Selected

I have a listbox and I want to do it. If my listbox is empty or not empty but no item selected, I want to disable button. But if listbox is not empty and it has a selected item, I want to enable button. I tried this but it doesn't work;

        if (lb.SelectedIndex == -1)
        {
            button1.Enabled = false;
        }
        else if(lb.SelectedIndex > -1)
        {
            button1.Enabled = true;
        }

Thank you for answers.

No need to use else if , just use else:

if (lb.SelectedIndex == -1)
{
   button1.Enabled = false;
}
else 
{
  button1.Enabled = true;
}

您首先将按钮设置为禁用,然后在您的列表框<your listboxid>_OnSelecIndexChanged事件上检查所选值并启用该按钮。

You need to add to listbox the SelectedIndexChanged event

In the properties of your listbox search for SelectedIndexChanged, then double click on it

在此处输入图片说明

Winforms selected index changed

private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
   if (lb.SelectedIndex == -1)
   {
     button1.Enabled = false;
   }
   else 
   {
     button1.Enabled = true;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM