Mark Gilbert's Blog

Science and technology, served light and fluffy.

You can’t see me! PropertyGrid, Databinding, and the Browsable() attribute

As I described in a previous post, I’ve been working with PropertyGrids of late.  Setting the grid’s SelectedObject property to an object is enough to get that object’s properties and values to appear in the grid, but rarely is that step sufficient for a real app.  That’s where attributes come in.  Using attributes (in particular, those found in the System.ComponentModel namespace) you can do things like attach a description for a property (using the Description() attribute), place them in a category (using the Category() attribute), or even hide them so that they don’t appear in the grid (using the Browsable() attribute).

In my case, the object I was working with exposed the database ID value, something I didn’t want the user to have to worry about.  So, I attached Browsable(False) to that property to hide it:

<Browsable(False)> _
Public Property ID()
As Long
    Get
        Return Me
._ID
   
End Get
    Set
(ByVal value As Long)
        Me._ID = value
   
End Set
End Property

That worked beautifully.  The ID property dropped out of the grid and I went on my merry way.  That is, until I opened up a form that had a databound drop down box based on a collection of these objects.  When I opened the form I was greeted with “Cannot bind to the new value member. Parameter name: value”.  This worked before.  What have I changed since then?

On a hunch, I tried backing out the changes I made to the class for the PropertyGrid.  Now, the drop down worked again.  After a little back and forth I determined that the Browsable() attribute was the problem.  Apparently, having that on the field not only hid it from the PropertyGrid, it rendered it unbindable.

The next best thing to having the field hidden from the grid completely was to make it read-only.  Would making it read-only still allow the drop down to bind to it?  I reworked the attributes on the class to test it:

<[ReadOnly](True), _
  Description("The format’s internal system ID"), _
  Category("Properties")> _
Public Property ID()
As Long
    Get
        Return Me
._ID
   
End Get
    Set
(ByVal value As Long)
        Me._ID = value
   
End Set
End Property

Sure enough, the drop down was happy again.  The field appears in the grid again, but this time it appears greyed out and isn’t editable. 

That’’ll do, ID.  That’ll do.

Advertisements

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

Sorry, the comment form is closed at this time.

%d bloggers like this: