Friday, March 5, 2010

Adding a new row to a DataForm in Silverlight

Below is a snippet of code that shows the code that can be used to programmatically add a new record to a DataForm. In this snippet, the DataForm is called _dataform and has a PagedCollectionView (list) of Person objects. The DataForm UI has a + button that adds records. We want to do the same thing, but with a different button, and also set some default or maybe even values that are not on the DataForm. To do this, we call AddNewItem() which is exactly what the + button does. Next we get the CurrentAddItem. This is of type Person so we can cast it as a Person and set any properties that are on the Person object, not just the ones on the DataForm.

public PagedCollectionView Persons { get; set; }

private void btnAdd_Click(object sender, RoutedEventArgs e)
{
_dataform.AddNewItem();

Person newPerson = Persons.CurrentAddItem as Person;
newPerson.Name = "zzz";

newPerson.City = "Tempe";
}
A working version of this code is available here. See the MainPageWithOnlyCustomButtons.xaml.cs file.

Another snippet that may come in handy for adding just like the above, but more for the scenario where you have not displayed any records in the DataForm, but you want to add a new one. This was the scenario I had when I used the DataForm in a Popup Window and showed only one record at a time or in this case needed to allow the user to add a new Person. Here is the snippet for that. The big difference is we have to populate the Persons variable with an empty list so that the DataForm knows what type of objects it is supposed to add. Otherwise, _datagrid will be null and the operation will have failed.
 
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
// the DataForm needs to know what we have a list of, so give it an empty list to start with
// then wehn we tell it to add a new one, it knows what to add/create.
Persons = new PagedCollectionView(new List<Person>());
_dataform.DataContext = null;
_dataform.DataContext = Persons;

_dataform.AddNewItem();
Person newPerson = Persons.CurrentAddItem as Person;
newPerson.Name = "zzz";
newPerson.City = "Tempe";
}

A working version of this code is available here. See the MainPageWithLoadOneRecordAtATime.xaml.cs file.

No comments: