1
votes

I have a listview and a button to remove items from that listview. The button needs to be disabled when they don't have any items selected, but enabled when they do. I've tried a different combination of events, but can't find one to properly disable the button...

When I disable the button when the listview loses focus, I can't remove the item because in order to click the button, they need to click outside the listview..

I'm hoping someone who's more experience in Visual Studio can help me find the correct combination of listview events to enable and disable the button according to whether or not they have an item selected.

2
Winforms, WPF, MVC or WebForms?Ivo
Updated the tags I think, but winformsmowwwalker
If any item is selected, the button is enabled. If no item is selected, the button is disabled.mowwwalker
Did you try the SelectedIndexChanged event of the listbox?Ivo

2 Answers

2
votes

Just subscribe the event ItemSelectionChanged like this (e.g. in the constructor):

listView1.ItemSelectionChanged += OnListViewItemSelectionChanged;

And in the event method enable / disable your button like that:

private void OnListViewItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
{
    button1.Enabled = (listView1.SelectedItems.Count > 0);
}
0
votes

I just tested some code to do this:

    private void Form1_Load(object sender, EventArgs e)
    {
        //Added some dummy items
        for(int i=0; i<10; i++)
            listView1.Items.Add("Item"+i.ToString());
        //Disable the button
        button1.Enabled = false;

    }

    private void listView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        button1.Enabled = (listView1.SelectedItems.Count > 0);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        listView1.Items.Remove(listView1.SelectedItems[0]);
    }

And this is working perfectly fine.

If you have some issues, you may please post your code here.