XamWebGrid – RequireEmptyContructor exceptions when adding new rows

[Infragistics] Devin Rader / Thursday, October 29, 2009

If you have the Add New Row feature of the XamWebGrid enabled, when the user attempts to add a new row by placing a cell in the row into edit mode the XamWebGrid automatically tries to instantiate a new instance of a data object of the same type that you have bound to the grid.  For example if you have bound a list of customer objects (eg List<Customer>) as the grids data source, when the end user tries to add a new row, the first thing the grid will try do is to create a new Customer object.

Normally this works fine because most objects include a default constructor that the grid can use to create this new object instance, but occasionally you need to bind an collection of objects that contain no default constructor.  In this case the grid will throw a RequiredEmptyConstructor exception when the end user attempts to add a new row.

The simplest fix for this is to make sure that your object has a default constructor:

public class Customer
{
    public Customer()
    {        
    }

    public Customer(string firstName, string lastName)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Of course adding a default constructor is not always possible since you may not have access to modify the object.  In that case you can use the grids DataObjectRequested event to intercept the request for the new object and provide one yourself.  For example, if the Customer class has no default constructor, in the DataObjectRequested event you could create an new instance with a set of default values:

private void xamWebGrid1_DataObjectRequested(object sender, Infragistics.Silverlight.DataObjectCreationEventArgs e)
{
    e.NewObject = new Customer("John", "Doe");
}

Now the grid will use the object you have instantiated to allow the end user to add a new row.