Home > Net >  Hide column in datagrid WPF
Hide column in datagrid WPF

Time:01-18

I have a table in a database which I want to display in a WPF DataGrid. However I want to hide the first column. This column defines Id's for all items. I need the Id's for further actions, but I don't want to show it in the DataGrid. I've tried the code below, but I do get an error, on the last line, that the index has to be bigger than 0.

DbMainTable.ItemsSource = dataHandler.visibleDatabaseTable.DefaultView;
DbMainTable.Columns[0].Visibility = Visibility.Hidden;

If anyone can help me, let me know.

CodePudding user response:

The problem is that when you are trying to set the visibility of the column it does not exist yet.
Try this:
In constructor:

DbMainTable.ItemsSource = dataHandler.visibleDatabaseTable.DefaultView;
DbMainTable.AutoGeneratedColumns  = DbMainTable_OnAutoGeneratedColumns;

below:

private void DbMainTable_OnAutoGeneratedColumns(object? sender, EventArgs e)
{
    DbMainTable.AutoGeneratedColumns -= DbMainTable_OnAutoGeneratedColumns;
    DbMainTable.Columns[0].Visibility = Visibility.Hidden;
}

CodePudding user response:

Could you provide more information about this issue? It is hard to guess what part of code is not working based on this.

But if I had to guess you use automatically generated columns and you try to hide this column before it is added to array of columns.

I event tried to do this with autogenerated columns and it gives me the same exception as you get.

To resolve this move this part of code somewhere where this datagrid (and its columns) is already loaded - for example to onl oaded event handler in code behind

To achieve this:

in code behind add this method

   private void DbMainTable_OnLoaded(object sender, RoutedEventArgs e)
    {
        DbMainTable.ItemsSource = dataHandler.visibleDatabaseTable.DefaultView;
        DbMainTable.Columns[0].Visibility = Visibility.Hidden;
    }

and in XAML:

    <DataGrid x:Name="DbMainTable"
                      Loaded="DbMainTable_OnLoaded"
                      Grid.Column="0" />

CodePudding user response:

If you need the id but don't want to see the column in the grid then I would think the simplest approach is not to add the column in the first place.

Work with the data which is in visibleDatabaseTable.

 private void DbMainTable_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
 {
     if ((string)e.Column.Header == "Id")
     {
         e.Cancel = true;
     }
 }

On your datagrid:

<Datagrid .....
     AutoGeneratingColumn="DbMainTable_AutoGeneratingColumn"/>
  • Related