Поделиться через


Как удалить или скрыть столбцы в элементе управления DataGrid в Windows Forms

Замечание

Элемент управления DataGridView заменяет и добавляет функции в элемент управления DataGrid; однако элемент управления DataGrid сохраняется как для обратной совместимости, так и для дальнейшего использования, если вы выберете. Дополнительные сведения см. в разделе Различия между управляющими элементами DataGridView и DataGrid в Windows Forms.

Вы можете программно удалить или скрыть столбцы в элементе управления DataGrid Windows Forms с помощью свойств и методов объектов GridColumnStylesCollection и DataGridColumnStyle (которые являются членами класса DataGridTableStyle).

Удаленные или скрытые столбцы по-прежнему существуют в источнике данных, к которым привязана сетка, и доступ к ним по-прежнему осуществляется программным способом. Они больше не отображаются в datagrid.

Замечание

Если приложение не обращается к определенным столбцам данных, и вы не хотите, чтобы они отображались в datagrid, то их, вероятно, не нужно включать в источник данных в первую очередь.

Удаление столбца из DataGrid программным способом

  1. В области объявлений формы объявите новый экземпляр класса DataGridTableStyle.

  2. Задайте для свойства DataGridTableStyle.MappingName таблицу в источнике данных, к которой нужно применить стиль. В следующем примере используется свойство DataGrid.DataMember, предполагается, что оно уже задано.

  3. Добавьте новый объект DataGridTableStyle в коллекцию стилей таблиц datagrid.

  4. Вызовите метод RemoveAt коллекции DataGrid объекта GridColumnStyles, указав индекс удаляемого столбца.

    ' 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);
    }
    

Скрытие столбца в DataGrid программным способом

  1. В области объявлений формы объявите новый экземпляр класса DataGridTableStyle.

  2. Установите свойство MappingName для DataGridTableStyle на таблицу в вашем источнике данных, к которой вы хотите применить стиль. В следующем примере кода используется свойство DataGrid.DataMember, которое предполагается, что оно уже задано.

  3. Добавьте новый объект DataGridTableStyle в коллекцию стилей таблиц datagrid.

  4. Скрыть столбец, задав для свойства Width значение 0, указав индекс столбца для скрытия.

    ' 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;
    }
    

См. также