Reputation: 73163
I have a listbox with some items in it. There are two buttons to add and remove listbox items. When closing the form, I need a confirmation message box if any changes are made to the listbox. So basically, form needs to know if items in listbox are changed. Which would be the right listbox event to set a changed flag?
Note: Of course I can handle this from Add button and Remove button clicks, but that's not the right way to do it. Ain't so? So no dirty tricks, but the right approach??
Upvotes: 3
Views: 918
Reputation: 81610
If just using a ListBox straight up, no, there isn't an event that will tell you the list has changed.
It's better to have the ListBox use a DataSource like BindingList which supports a ListChanged event.
private BindingList<string> myList = new BindingList<string>();
private bool isDirty;
public Form1()
{
InitializeComponent();
myList.Add("aaa");
myList.Add("bbb");
myList.Add("ccc");
myList.ListChanged += new ListChangedEventHandler(myList_ListChanged);
listBox1.DataSource = myList;
}
public void myList_ListChanged(object sender, ListChangedEventArgs e)
{
isDirty = true;
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("IsDirty = " + isDirty.ToString());
myList.Add("ddd");
MessageBox.Show("IsDirty = " + isDirty.ToString());
}
Upvotes: 3
Reputation: 48596
I think you should be setting the "dirty" flag from the methods that are called to actually perform the item addition and removal. That way, if you decide to add additional methods for interacting with the list box (a context menu, keyboard shortcut, etc.) your logic is all in one place and ready to be re-used.
So your add method would look something like this:
public void Add(MyListboxItem itemToAdd)
{
// Adding code here
// Set the boolean flag to true
this.IsDirty = true;
}
That's a somewhat naive method, though, since now adding an item and then removing it results in a prompt, even though the list hasn't actually changed from its original state. If the size of your list isn't too big, another option would be to make a copy of the backing data when it is first loaded, and then to compare the final data against that copy. If there's no differences, you don't have to prompt.
Upvotes: 1