Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Datagrid binding and column display

Tags:

c#

wpf

I have datatable as Item source for DataGrid, this datatable has lots of columns. Is it possible to display few columns instead all of them without creating a new table?

like image 855
Wild Goat Avatar asked May 10 '12 13:05

Wild Goat


2 Answers

Yes, it is. Just mark AutoGenerateColumns=False and manually define your columns. You can use normal text-bound columns, checkbox columns, custom XAML template columns and more, as you can see in the documentation.

<DataGrid ItemsSource="{Binding DataSource}" AutoGenerateColumns="False" >
    <DataGrid.Columns>
    <DataGridTextColumn Header="Simple Value"
                      Binding="{Binding SimpleValue}" Width="*" />
     <DataGridTemplateColumn Width="*" Header="Complex Value">
        <DataGridTemplateColumn.CellTemplate>
          <DataTemplate>
            <StackPanel>
               <TextBox Text="{Binding ComplexValue}"/>
               <TextBox Text="{Binding ComplexValue2}"/>
            </StackPanel>
          </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
      </DataGridTemplateColumn>
    </DataGrid.Columns>
  </DataGrid>
like image 118
Avner Shahar-Kashtan Avatar answered Oct 13 '22 19:10

Avner Shahar-Kashtan


Also, you can handle DataGrid.AutoGeneratingColumn event and set e.Cancel = true for columns that you don't want to be shown. This way you don't have to manually define columns that you want to show.

like image 30
Stipo Avatar answered Oct 13 '22 17:10

Stipo