1

How to add a delete column in datagrid in WPF, when i add this column, got Items collection must be empty before using ItemsSource Error

 <DataGrid AutoGenerateColumns="True" ItemsSource="{Binding}" Name="dgStatus" 
                  HorizontalAlignment="Left" Margin="10,23,0,0" VerticalAlignment="Top" 
                  RenderTransformOrigin="-23.633,-5.198" Height="364" Width="811" 
                  CellEditEnding="myGrid_CellEditEnding" >
                <DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Content="Delete" x:Name="btnDelete" Click="btnDelete_Click"></Button>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid>
ControlPoly
  • 717
  • 2
  • 10
  • 21
  • I think you may find you answer here [http://stackoverflow.com/questions/6882306/datagridtemplatecolumn-items-collection-must-be-empty-before-using-itemssource] – sohaiby Aug 07 '13 at 10:33

1 Answers1

2

You missed <DataGrid.Columns> tag

<DataGrid AutoGenerateColumns="True" ItemsSource="{Binding}" Name="dgStatus" 
          HorizontalAlignment="Left" Margin="10,23,0,0" VerticalAlignment="Top" 
          RenderTransformOrigin="-23.633,-5.198" Height="364" Width="811" 
          CellEditEnding="myGrid_CellEditEnding" >

    <DataGrid.Columns>

            <DataGridTemplateColumn>
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Button Content="Delete" x:Name="btnDelete" Click="btnDelete_Click"></Button>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
           </DataGridTemplateColumn>

    </DataGrid.Columns>

</DataGrid>
Nitesh
  • 7,261
  • 3
  • 30
  • 25
  • 2
    adding to answer. when you add element under datagrid element. that will be appended as item of datagrid. so in this case you can item as well as you want to update thru ItemsSource property of the DataGrid. that why you get this error. – JSJ Aug 07 '13 at 11:43