views:

34

answers:

0

What is a clean way of handling in-grid edit (specifically: adding new rows) with a DataGridView bound to an in-memory collection?

Background: I have a tree structure; for the sake of simplicity, let's assume Directories and Files (my own classes). I use a TreeView to navigate the Directory structure, and populate a DataGridView with the contents of the Directory selected in the TreeView - so far, so good. The DGV uses a BindingSource, which is bound to a List which I populate when selected Directory changes; using BindingList (or something else completely) is a possible option, BS+List is just the current setup.

My problem is with in-grid editing, specifically adding new items. First, using the default no-argument File constructor isn't good enough, since I need to pass in it's parent Directory. This is solvable by handling the DataSource's AddingNew event, where I can get the currently selected Directory, use the correct File constructor, and set the NewObject property of the event. So far so good...

Thing is, AddingNew is called as soon as the empty row in the DGV is clicked. So if the user clicks the empty row, but decides he doesn't want the item after all, I get a BS.AddingNew event, as well as BS.ListChanged with ItemAdded, followed by a BS.ListChanged with ItemDeleted when the user hit ESC or navigates away from the DGV without entering any values. I could use ItemAdded to add the File to it's Parent directory, but since ItemDeleted happens after the item is removed, I don't get a chance to undo this - besides, it all feels pretty dirty... not to mention that a File can't really be created without a name (and ItemAdded happens as soon as the user starts editing the cell).

I guess my question boils down to whether it's possible to get a "New item has been added" kind of event only if the user actually decides to add the new item?

Any suggestions welcome - I'd prefer something clean that doesn't take a zillion lines of code to achieve. Everything's possible, though, including implementing interfaces on the File class, using/writing some other container instead of BindingSource+List, etc. I'm really looking for the clean way of setting up things - have I overlooked a simple & obvious solution, or will I have to do a custom collection implementing the ICancelAddNew interface?

Thanks in advance :)