Mark Gilbert's Blog

Science and technology, served light and fluffy.

Focus, grasshopper!

I was working with a WinForms form that contained a PropertyGrid control, and hit an interesting problem when I was trying to save updates made to the values in it.  I was using the PropertyGrid as a quick and dirty way to provide an admin screen where the user could select an item from a list, see the properties for that item in the grid, edit them as needed, and then hit Save.  The problem was that Save wasn’t always picking up my changes.

The Save function was defined on the app’s menu, and it invoked the form’s Save method.  I assigned a shortcut of Ctrl-S to this menu item.  In the course of my testing I was finding that if I typed a new value into the grid and then hit Ctrl-S, my new value wasn’t being saved.  In stepping through the code, the grid’s SelectedObject property – which would normally contain all of the values being displayed in the grid – wasn’t getting the one I was just working on.  If I modified the value and used my mouse to select the Save option from the menu, then it worked.

Clearly, strange things are afoot at the Circle-K.

What if I modified a value in the grid, then clicked somewhere else in the grid, then hit Ctrl-S?  That worked.  Ok, now things are making more sense – the problem is focus.  The focus was still on the item I just edited, so SelectedObject wasn’t being updated with what I just typed in.  When I hit Ctrl-S, the focus wasn’t changed at all, but it did change when I clicked the menu item for Save.

The solution proved to be quite simple.  At the beginning of my form’s Save method, I added this line:

Me.MainGrid.Focus

That forced the focus to be moved away from whichever field in the grid I was just working on, thereby forcing the SelectedObject to be updated with the latest values from the grid.  That, in turn, allowed both pathways – keyboard shortcut and menu click – to work.

Advertisements

January 14, 2010 - Posted by | Visual Studio/.NET

1 Comment

  1. […] January 18, 2010 Posted by markegilbert in Visual Studio/.NET. trackback As I described in a previous post, I’ve been working with PropertyGrids of late.  Setting the grid’s SelectedObject property […]

    Pingback by You can’t see me! PropertyGrid, Databinding, and the Browsable() attribute « Mark Gilbert’s Blog | January 18, 2010


Sorry, the comment form is closed at this time.

%d bloggers like this: