44

I'm getting nuts here with this:

ObservableCollection<Employee> list = new ObservableCollection<Employee>();
dgEmployees.ItemsSource = list;

When you debug the list variable, it's empty (list.Count =0), but then I bind it to a DataGrid (WPFToolkit), it shows me a blank row.

In immediate window, for dgEmployees.Items it's showing:

dgEmployees.Items[0]
{NewItemPlaceholder}

and

dgEmployees.Items[0].GetType()
{Name = "NamedObject" FullName = "MS.Internal.NamedObject"}
[System.RuntimeType]: {Name = "NamedObject" FullName = "MS.Internal.NamedObject"}

It seems to happen after I've put this Datagrid into a TabControl, but I'm not sure it has something to do with it.

Does anyone know how to remove this blank row?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Junior Mayhé
  • 16,144
  • 26
  • 115
  • 161
  • 2
    You should accept the other answer, it's better than yours – reggaeguitar Dec 11 '14 at 22:00
  • I got the exception `System.InvalidCastException: 'Unable to cast object of type 'MS.Internal.NamedObject' to type MyClass` in external code through one of my bindings. Found out this extra empty line was the culprit! But the answer of Pablonete was better for me. – ffonz Jan 15 '22 at 19:34

3 Answers3

99

The same problem persist in WPF 4.0 version of DataGrid, and it is caused by the add-new row which it shows automatically for ObservableCollection ItemsSource. Setting IsReadOnly as True it's too radical IMHO.
I solved it by disabling CanUserAddRows property if you don't need that behavior, but you still want cells to be modified:

CanUserAddRows="False"

Pablonete
  • 1,504
  • 1
  • 14
  • 11
  • agreed unless it is truly readonly then that seems over kill. – Jon Mar 23 '11 at 12:23
  • 1
    Thanks, this answer helped me a lot more than the IsReadOnly which in my case had some side effects that I didn't want. – Dessus Jul 07 '13 at 03:04
  • 3
    Can we mark this as the answer as IsReadOnly does have side-effects while this does not? – Shreyas Dec 23 '14 at 14:47
25

I've got it

on Datagrid XAML, put the attribute:

IsReadOnly="True"
Junior Mayhé
  • 16,144
  • 26
  • 115
  • 161
  • This is not correct answer. This is correct - https://stackoverflow.com/a/5064128/987850 – 23W Feb 13 '23 at 13:43
5

CanUserAddRows="False" and IsReadOnly="True" combination of both is better to ensure any additional inconveniences.

KyloRen
  • 2,691
  • 5
  • 29
  • 59
Sawarkar vikas
  • 315
  • 1
  • 5
  • 9
  • 1
    you are suggesting he use two overlapping functionalities where either one will suffice and in fact `IsReadOnly = true` will remove other functionality with no gain at all. – NappingRabbit Oct 24 '17 at 18:12