For a ListBox (With Selection mode set to One), I wish to track whether there's a selected item or none selected. To do so, I subscribed a method to SelectedIndexChanged and checked if the SelectedIndex is -1 or not. However, I noticed that the event doesn't fire after calling Items.Clear(), even though SelectedIndex changes to -1 (if it wasn't already -1).
Why doesn't it fire? I know I can work around this by assigning -1 to SelectedIndex before clearing the list. But is there a better way?
Here's a simple code to replicate this:
using System;
using System.Windows.Forms;
namespace ns
{
class Program
{
static ListBox lst = new ListBox();
public static void Main()
{
lst.SelectedIndexChanged += new EventHandler(lst_SelectedIndexChanged);
lst.Items.Add(1);
Console.WriteLine("Setting selected index to 0...");
lst.SelectedIndex = 0; //event fire here
Console.WriteLine("(Selected Index == {0})", lst.SelectedIndex);
Console.WriteLine("Clearing all items...");
lst.Items.Clear(); //event *should* fire here?!
//proof that the selected index has changed
Console.WriteLine("(Selected Index == {0})", lst.SelectedIndex);
}
static void lst_SelectedIndexChanged(object sender, EventArgs e)
{
Console.WriteLine("[!] Selected Index Changed:{0}", lst.SelectedIndex);
}
}
}
Edit: I am considering making a custom list by making a class that inherits from ListBox, or by making a user control. However I'm not sure how to approach this. Any ideas on hiding/overriding the clear method using either inheritance/userControl? Would it require hiding/overriding other methods as well or is there a way to avoid this?