Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF DataGrid - Event for New Rows?

Tags:

c#

wpf

datagrid

I'm using the WPF DataGrid (.Net 3.5 SP 1 version from the Toolkit)

What event can I subscribe to, to detect when a new row is added? (e.g. when the user moves the cursor down or presses Enter a new blank row gets added to the grid).

Eventually what I want to do is use that event to calculate some default values and put them in the new row.

The grid is bound to a DataTable, if that makes any difference.

like image 493
codeulike Avatar asked Jan 06 '11 17:01

codeulike


2 Answers

The event you are looking for is DataGrid.AddingNewItem event. This event will allow you to configure the new object as you want it and then apply it to the NewItem property of the AddingNewItemEventArgs.

XAML:

<DataGrid Name="GrdBallPenetrations"
      ItemsSource="{Binding BallPenetrationCollection}" 
      SelectedItem="{Binding CurrentSelectedBallPenetration}"
      AutoGenerateColumns="False" 
      IsReadOnly="False"
      CanUserAddRows="True"
      CanUserDeleteRows="True"
      IsSynchronizedWithCurrentItem="True"
      AddingNewItem="GrdBallPenetrations_AddingNewItem">

Code behind in C#:

private void GrdBallPenetrations_AddingNewItem(object sender,
    AddingNewItemEventArgs e)
{
    e.NewItem = new BallPenetration
    {
        Id              = Guid.NewGuid(),
        CarriageWay     = CariageWayType.Plus,
        LaneNo          = 1,
        Position        = Positions.BetweenWheelTracks
    };
}
like image 162
dayneo Avatar answered Sep 21 '22 10:09

dayneo


Objects are persisted (inserted or updated) when the user leaves a row that he was editing. Moving to another cell in the same row updates the corresponding property through data binding, but doesn't signal the Model (or the Data Access Layer) yet. The only useful event is DataGrid.RowEditEnding. This is fired just before committing the modified row.

XAML

<DataGrid ... 
          RowEditEnding="MyDataGrid_RowEditEnding">
</DataGrid>

Code Behind

private void MyDataGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e) 
{    // Only act on Commit
    if (e.EditAction == DataGridEditAction.Commit)
    {
         var newItem = e.Row.DataContext as MyDataboundType;
         if (newItem is NOT in my bound collection) ... handle insertion...
    } 
}

All credits for this solution go to Diederik Krolls (Original Post). My respect.

like image 9
Califf Avatar answered Sep 19 '22 10:09

Califf