Share via


How to: Remove Autogenerated Columns from a Windows Forms DataGridView Control

When your DataGridView control is set to autogenerate its columns based on data from its data source, you can selectively omit certain columns. You can do this by calling the Remove method on the Columns collection. Alternatively, you can hide columns from view by setting the Visible property to false. This technique is useful when you want to display the hidden columns in certain conditions, or when you need to access the data in the columns without displaying it.

To remove autogenerated columns

  • Call the Remove method on the Columns collection.

    With dataGridView1
        .AutoGenerateColumns = True
        .DataSource = customersDataSet
        .Columns.Remove("Fax")
    End With
    
    dataGridView1.AutoGenerateColumns = true;
    dataGridView1.DataSource = customersDataSet;
    dataGridView1.Columns.Remove("Fax");
    

To hide autogenerated columns

  • Set the column's Visible property to false.

    dataGridView1.Columns("CustomerID").Visible = False
    
    dataGridView1.Columns["CustomerID"].Visible = false;
    

Example

Private Sub BindDataAndInitializeColumns()

    With dataGridView1
        .AutoGenerateColumns = True
        .DataSource = customersDataSet
        .Columns.Remove("Fax")
        .Columns("CustomerID").Visible = False
    End With

End Sub
private void BindDataAndInitializeColumns()
{
    dataGridView1.AutoGenerateColumns = true;
    dataGridView1.DataSource = customersDataSet;
    dataGridView1.Columns.Remove("Fax");
    dataGridView1.Columns["CustomerID"].Visible = false;
}

Compiling the Code

This example requires:

  • A DataGridView control named dataGridView1 bound to a table that contains Fax and CustomerID columns, such as the Customers table in the Northwind sample database.

  • References to the System and System.Windows.Forms assemblies.

See Also

Reference

DataGridView
System.Windows.Forms.DataGridView.AutoGenerateColumns
System.Windows.Forms.DataGridView.Columns
System.Windows.Forms.DataGridViewColumnCollection.Remove
System.Windows.Forms.DataGridViewColumn.Visible

Other Resources

Displaying Data in the Windows Forms DataGridView Control