Adding Rows to a WPF DataGrid Programatically

If you are going to let your users edit data in a DataGrid, at some point you will want to allow them to add records to the grid.  Adding a new row is simplicity itself, you just add a new item to the collection that is acting as your data source.  Suppose we are working with the data source from my prior DataGrid article.  We just add a new Account object to our Accounts collection, like this:


Accounts.Add(New Account())

This adds a new row to the DataGrid but it doesn’t put the grid into edit mode with the new row as the currently selected row.  Doing this is a bit more involved.  First we need to set the currently selected row by setting MyGrid.SelectedIndex to the index of the Account object in our collection.  For a newly added row, that would be Accounts.Count - 1. i.e. the last object in the collection.  Then we need to set the currently selected column by setting MyGrid.CurrentColumn to the first column in the row.  This will always be MyGrid.Columns(0).  Then we need to put the grid into edit mode by calling MyGrid.BeginEdit(), which puts the currently selected cell into edit mode.  Finally we need to give the grid focus by calling MyGrid.Focus().  The complete code to add a row and set the grid into edit mode looks like this:


' Add a new account to our list of accounts
Accounts.Add(New Account())
' Make the newly added account the current row of the grid
MyGrid.SelectedIndex = Accounts.Count - 1
' Make the ID field the current column of the grid
MyGrid.CurrentColumn = MyGrid.Columns(0)
' Put the grid into editing mode
MyGrid.BeginEdit()
' Give the grid control focus
MyGrid.Focus()

It seems like nothing is ever easy with this stuff.  Sigh.

Leave a Reply