Data for Silverlight
Add and Remove Items
The Sample Application > Implement the Client Side > Add and Remove Items

Unlike most WinForms grids, the Silverlight DataGrid control does not allow users to add or remove items from the grid. We use the buttons already on the page for that. The first thing to do is connect the event handlers on the page constructor:

C#
Copy Code
// Load data, hook up event handlers
public Page()
{
  InitializeComponent();
  LoadData();

  _gridCategories.SelectionChanged += _gridCategories_SelectionChanged;
  _btnAdd.Click += _btnAdd_Click;
  _btnRemove.Click += _btnRemove_Click;
}

The event handlers are simple, they look like regular ADO.NET code you would write on a WinForms application:

C#
Copy Code
// Add a new row
private void _btnAdd_Click(object sender, RoutedEventArgs e)
{
  DataTable dt = _ds.Tables["Categories"];
  DataRow newRow = dt.NewRow();
  newRow["CategoryName"] = "New category";
  newRow["Description"] = "This is a new category...";
  dt.Rows.Add(newRow);
}
 
// Delete a row
private void _btnRemove_Click(object sender, RoutedEventArgs e)
{
  DataRowView drv = _gridCategories.SelectedItem as DataRowView;
  if (drv != null)
  {
    DataRow dr = drv.GetRow();
    dr.Delete();
  }
}
     

If you run the application now, you can add, remove, and modify the items displayed in the grids.

Note: The DataSet we are using contains not only the tables you see, but also the DataRelation that connects the two tables. That relation came from the MDB file and was downloaded from the server along with the data. The relation has a ChildKeyConstraint property that specifies, among other things, that delete operations cascade through the tables. In other words, if you delete a category, all products that belong to that category are also automatically deleted.

See Also