How to enable a button if an item in a listbox is selected

怎甘沉沦 提交于 2019-12-14 03:18:24

问题


I tried this but it doesn't work. They're still greyed out even when I select stuff.

btnVoirFiche.Enabled = false;
btnEchangerJoueur.Enabled = false;
if (lstJoueurs.SelectedIndex != -1)
        {
            btnVoirFiche.Enabled = true;
            btnEchangerJoueur.Enabled = true;
        }
        else
        {
        }

回答1:


You'll want to handle the ListBox.SelectedIndexChanged event, and within your handler you're going to check if the specific value is the selected one, and then set you button's enable property accordingly.

Something like this:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if(listBox1.SelectedIndex != -1)
    {
        btnVoirFiche.Enabled = true;
        btnEchangerJoueur.Enabled = true;
    }
    else
    {
       //whatever you need to test for
    }
}

Cheers

EDIT: I'm not too sure what your logic for button's enabled property is, so my answer is pretty generic. If you add details to you question, I'll adapt accordingly.




回答2:


Hook into SelectedIndexChanged event and put your code inside of it

private void lstJoueurs_SelectedIndexChanged(object sender, EventArgs e)
{
    if (lstJoueurs.SelectedIndex != -1)
    {
        btnVoirFiche.Enabled = true;
        btnEchangerJoueur.Enabled = true;
    }
 }



回答3:


As an alternative, and using mrlucmorin's answer, you could use the listbox's SelectedItem which will return null if nothing is selected.



来源:https://stackoverflow.com/questions/22084919/how-to-enable-a-button-if-an-item-in-a-listbox-is-selected

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!