220

I bind my datagrid using

//fill datagrid
public DataTable GameData
{
    get
    {
        DataSet ds = new DataSet();
        FileStream fs = new FileStream(IMDB.WebPage.Class.Config.XMLPath,
        FileMode.Open, FileAccess.Read);
        StreamReader reader = new StreamReader(fs, Encoding.Default);
        ds.ReadXml(reader);
        fs.Close();
        DataTable temp = ds.Tables[0];
        return ds.Tables[0];
     }
 }

For some reason I get an empty row at the bottom. And sometimes after clicking on some buttons and checkboxes in the grid, more empty rows are added.

Why is this? And how do I block this?

Kate Gregory
  • 18,808
  • 8
  • 56
  • 85
WtFudgE
  • 5,080
  • 7
  • 47
  • 59

5 Answers5

500

Sounds like you probably have CanUserAddRows set to true for the DataGrid. Just add

CanUserAddRows="false"

to the XAML.

Tomi Junnila
  • 7,443
  • 3
  • 28
  • 24
  • 14
    keep in mind that even if the check box in the grid's properties is unchecked you have to explicitly add that line of code to hide the additional row (or check and uncheck the check box) – Tobias Valinski Nov 28 '13 at 10:39
  • 6
    If you don't want code behind, add attribute CanUserAddRows="False". It looks like a bug in WPF that you have to set it to false explicitly. – ZZZ Dec 31 '13 at 00:33
  • I rather have the opposite problem. It does not create an empty row, while I'd rather want that. – Shimmy Weitzhandler Oct 30 '19 at 00:52
26

It also works with the attribute:

IsReadOnly="true"
ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
Arti
  • 2,993
  • 11
  • 68
  • 121
14

If your backing collection that implements IEditableCollectionView returns true from its CanAddNew method, the DataGrid will assume that is what you want to do.

There's a good overview here:Overview of the editing features in the WPF DataGrid

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Alastair Maw
  • 5,373
  • 1
  • 38
  • 50
4

If you're creating DataGrid on-the-fly through Source Code...

DataGrid grid = new DataGrid();

grid.CanUserAddRows = false;

//... 
grid.AutoGenerateColumns = false;
grid.Margin = new Thickness(10,20,10,10);
grid.VerticalAlignment = VerticalAlignment.Top;
grid.ItemsSource = //... and so on
Kate Gregory
  • 18,808
  • 8
  • 56
  • 85
Francisco Campos
  • 1,191
  • 8
  • 16
1

Though the OP was asking how to REMOVE the empty row, the title isn't specific, and this article appeared in my search while trying to figure out how to ADD the empty row. I found that, for the empty row to appear, it not only needs to have CanUserAddRows="True" but the ItemsSource needs to have a default constructor public MyClass () { }.

AdvApp
  • 1,094
  • 1
  • 14
  • 27