Compartilhar via


Como: Excluir ou ocultar colunas no controle Windows Forms DataGrid

ObservaçãoObservação

O DataGridView controle substitui e adiciona funcionalidade para o DataGrid controle; No entanto, o DataGrid controle é mantido para compatibilidade com versões anteriores e o uso futuro, se você escolher. Para obter mais informações, consulte Diferenças entre o DataGridView do Windows Forms e controles DataGrid.

Programaticamente, você pode excluir ou ocultar colunas nos formulários do Windows DataGrid controle usando as propriedades e métodos para a GridColumnStylesCollection e DataGridColumnStyle objetos (que são membros da DataGridTableStyle classe).

As colunas excluídas ou ocultas ainda existem na fonte de dados, a grade está vinculado e ainda podem ser acessados por meio de programação. Eles apenas não são mais visíveis do DataGrid.

ObservaçãoObservação

Se seu aplicativo não acessar determinadas colunas de dados e não deseja exibi-los no datagrid, em seguida, provavelmente não é necessário para incluí-los em primeiro lugar na fonte de dados.

Para excluir uma coluna de DataGrid programaticamente

  1. Na área de declarações do formulário, declare uma nova instância de DataGridTableStyle classe.

  2. Definir o DataGridTableStyle.MappingName propriedade para a tabela na fonte de dados que você deseja aplicar o estilo. O exemplo a seguir usa a DataGrid.DataMember propriedade, que ele assume que é já definido.

  3. Adicionar a nova DataGridTableStyle o objeto para a datagrid tabela estilos coleção.

  4. Chamar o RemoveAt método o DataGriddo GridColumnStyles coleção, especificando o índice da coluna da coluna a ser excluído.

    ' Declare a new DataGridTableStyle in the
    ' declarations area of your form.
    Dim ts As DataGridTableStyle = New DataGridTableStyle()
    
    Sub DeleteColumn()
       ' Set the DataGridTableStyle.MappingName property
       ' to the table in the data source to map to.
       ts.MappingName = DataGrid1.DataMember
    
       ' Add it to the datagrid's TableStyles collection
       DataGrid1.TableStyles.Add(ts)
    
       ' Delete the first column (index 0)
       DataGrid1.TableStyles(0).GridColumnStyles.RemoveAt(0)
    End Sub
    
    // Declare a new DataGridTableStyle in the
    // declarations area of your form.
    DataGridTableStyle ts = new DataGridTableStyle();
    
    private void deleteColumn()
    {
       // Set the DataGridTableStyle.MappingName property
       // to the table in the data source to map to.
       ts.MappingName = dataGrid1.DataMember;
    
       // Add it to the datagrid's TableStyles collection
       dataGrid1.TableStyles.Add(ts);
    
       // Delete the first column (index 0)
       dataGrid1.TableStyles[0].GridColumnStyles.RemoveAt(0);
    }
    

Para ocultar uma coluna em um DataGrid programaticamente

  1. Na área de declarações do formulário, declare uma nova instância de DataGridTableStyle classe.

  2. Definir o MappingName propriedade da DataGridTableStyle a tabela na fonte de dados que você deseja aplicar o estilo. O seguinte exemplo de código usa a DataGrid.DataMember propriedade, que ele assume que é já definido.

  3. Adicionar a nova DataGridTableStyle o objeto para a datagrid tabela estilos coleção.

  4. Ocultar a coluna definindo seu Width a propriedade como 0, especificando o índice da coluna da coluna para ocultar.

    ' Declare a new DataGridTableStyle in the
    ' declarations area of your form.
    Dim ts As DataGridTableStyle = New DataGridTableStyle()
    
    Sub HideColumn()
       ' Set the DataGridTableStyle.MappingName property
       ' to the table in the data source to map to.
       ts.MappingName = DataGrid1.DataMember
    
       ' Add it to the datagrid's TableStyles collection
       DataGrid1.TableStyles.Add(ts)
    
       ' Hide the first column (index 0)
       DataGrid1.TableStyles(0).GridColumnStyles(0).Width = 0
    End Sub
    
    // Declare a new DataGridTableStyle in the
    // declarations area of your form.
    DataGridTableStyle ts = new DataGridTableStyle();
    
    private void hideColumn()
    {
       // Set the DataGridTableStyle.MappingName property
       // to the table in the data source to map to.
       ts.MappingName = dataGrid1.DataMember;
    
       // Add it to the datagrid's TableStyles collection
       dataGrid1.TableStyles.Add(ts);
    
       // Hide the first column (index 0)
       dataGrid1.TableStyles[0].GridColumnStyles[0].Width = 0;
    }
    

Consulte também

Tarefas

Como: Alterar os dados exibidos em tempo de execução no controle Windows Forms DataGrid

Como: Adicionar tabelas e colunas para o controle DataGrid do Windows Forms