2

The Problem

I use a DataGrid with CanUserAddRows="true", so the user can use the placeholder row at the bottom to add entries, but I get unwanted behaviour:

When the user cancels editing of the placeholder row using the ESC key and then selects another row, the DataGrid will refresh and an additional empty row appears.

Is there a way to prevent this empty row from being added?


The Code

MainWindow.xaml

<Window x:Class="DataGridTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <DataGrid Name="dgCommands" Margin="5"/>
    </Grid>
</Window>

MainWindows.xaml.cs

using System.Collections.Generic;
using System.Windows;

namespace DataGridTest
{
    public partial class MainWindow : Window
    {
        private List<Command> commands = new List<Command>();

        public MainWindow()
        {
            InitializeComponent();

            commands.Add(new Command
            {
                Request = "Marco",
                Response = "Polo"
            });

            dgCommands.ItemsSource = commands;
        }
    }

    public class Command
    {
        public string Request
        {
            get;
            set;
        }

        public string Response
        {
            get;
            set;
        }
    }
}
2
  • 1
    I think you should take a look at the events "AddingNewItem" and / or "RowEditEnding" of the DataGrid then you should be able to prevent the adding row. Sep 8, 2015 at 12:21
  • @Bertrand Thanks for the tip! Even though AddingNewItem doesn't seem to have a fitting option, RowEditEnding looks like the place to start. But it seems, cancelling only prevents the row from being shown in the DataGrid, it will still be added to the list of items and the DataGrid will keep trying to show it, so you have to keep cancelling the event. Sep 8, 2015 at 14:08

1 Answer 1

0

You can check EditAction in CellEditEnding event:

add event to grid in yout xaml:

<DataGrid Name="dgCommands" Margin="5" CellEditEnding="dataGrid_CellEditEnding" />

and in your code behind:

private void dataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e) {
        //If pressed ESC key
        if (e.EditAction == DataGridEditAction.Cancel) {
            return;
        }
        else {
            //Save new row
        }
    }
1
  • As I said, the empty row gets added, even though DataGridEditAction is set to Cancel. And you don't have to save the row on your own, its handled by the DataGrid. Thats where the problem arises - I can't control the addition of rows. Sep 8, 2015 at 14:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.