Junior Mayhe
Junior Mayhe

Reputation: 16411

How to remove DataGrid's blank row when binding to a ObservableCollection<T>?

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?

Upvotes: 44

Views: 41056

Answers (3)

Sawarkar vikas
Sawarkar vikas

Reputation: 345

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

Upvotes: 5

Pablonete
Pablonete

Reputation: 1524

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"

Upvotes: 100

Junior Mayhe
Junior Mayhe

Reputation: 16411

I've got it

on Datagrid XAML, put the attribute:

IsReadOnly="True"

Upvotes: 26

Related Questions