If you have worked with WPF DataGrid you will be familiar with the problem of extra blank column which appears after last column inside DataGrid. It looks ugly and definitely you would like to get rid of that column. In this post I am going to talk about two ways to hide that extra column. First approach will be based on popular MVVM pattern and second will use a simple event in code behind file to hide that column. You can download a ready to run code from here which demonstrate both scenarios.
In both scenarios I am setting code behind file as DataContext for my MainWindow and I am binding my DataGrid with a property 'MyView', declared in code behind file, which returns a DataTable as DataView.
1: public DataView MyView
2: {
3: get
4: {
5: DataTable table = new DataTable();
6: DataColumn column1 = new DataColumn("Column1");
7: DataColumn column2 = new DataColumn("Column2");
8: table.Columns.Add(column1);
9: table.Columns.Add(column2);
10: //create ten rows
11: for (int i = 0; i < 10; i++)
12: {
13: DataRow newRow = table.NewRow();
14: newRow["Column1"] = i.ToString();
15: newRow["Column2"] = (i + 100).ToString();
16: table.Rows.Add(newRow);
17: }
18: return table.AsDataView();
19: }
20: }
In MVVM based scenario I am encapsulating my DataGrid inside a Grid. Inside Grid you have to declare same number of columns as in your DataView. I am declaring two columns in my Grid because I have two columns in my DataView. I am setting width of my Grid's columns equal to the actual width of columns inside DataGrid.
1: <Grid>
2: <Grid>
3: <Grid.ColumnDefinitions>
4: <ColumnDefinition Width="{Binding ElementName=Col1, Path=ActualWidth}"/>
5: <ColumnDefinition Width="{Binding ElementName=Col2, Path=ActualWidth}"/>
6: </Grid.ColumnDefinitions>
7:
8: <DataGrid Grid.Column="0" Grid.ColumnSpan="2" ItemsSource="{Binding Path=MyView}" AutoGenerateColumns="False">
9: <DataGrid.Columns>
10: <DataGridTextColumn MinWidth="100" x:Name="Col1" Header="Column1" Binding="{Binding Path=Column1}"/>
11: <DataGridTextColumn MinWidth="100" x:Name="Col2" Header="Column 2" Binding="{Binding Path=Column2}"/>
12: </DataGrid.Columns>
13: </DataGrid>
14: </Grid>
15: </Grid>
The second scenario, a non-MVVM based scenario, is sample. I am just handling DataGrid_AutoGeneratingColumn' event in code behind file.
1: <DataGrid ItemsSource="{Binding Path=MyView}" AutoGenerateColumns="True" AutoGeneratingColumn="DataGrid_AutoGeneratingColumn"/>
1: private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
2: {
3: if(e.Column.Header == "Column2")
4: e.Column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
5: }