Thursday, 28 January 2010

Fixing the " 'Telerik.Web.UI.GridInsertionObject' does not contain a property with the name" problem

Telerik's RadGrid has a handy possibility to insert a new object. Works fine with DataTables, but since I sure prefer using ObjectDataSources, sometimes I get the abovementioned exception when clicking the Insert button whenever the grid is empty.

The problem is, the grid can't figure out the type of the new record when it doesn't have any records yet. This is sorta silly, since it is bound to an ObjectDataSource object and (theoretically) could get the class name from it. Anyway, it just creates an instance of Telerik.Web.UI.GridInsertionObject and then complains that it can't do the databinding.

There are tons of solutions out there, even provided by the Telerik team, and they typically involve a lot of manual labour. Typically you would create an object yourself or provide some Dictionary with all properties initialized etc. Not exactly a DRY style of work.

My solution is.. just return a generic List rather than an Enumerable for the Select method of your ObjectDataSource. For example, this
Return From product In Me.FetchAll Where product.CategoryId = categoryId
will give an exception when trying to add a record. Change it to
Return (From product In Me.FetchAll Where product.CategoryId = categoryId).ToList()
and you'll be fine.