Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
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.
Another approach is to prevent columns from being auto-generated in the first place by setting the ColumnMapping property of the underlying DataColumn to Hidden. This tells the DataGridView to skip creating a column for that particular data column during auto-generation.
To remove autogenerated columns
Call the Remove method on the Columns collection.
dataGridView1.AutoGenerateColumns = true; dataGridView1.DataSource = customersDataSet; dataGridView1.Columns.Remove("Fax");
With dataGridView1 .AutoGenerateColumns = True .DataSource = customersDataSet .Columns.Remove("Fax") End With
To hide autogenerated columns
Set the column's Visible property to
false
.dataGridView1.Columns["CustomerID"].Visible = false;
dataGridView1.Columns("CustomerID").Visible = False
To prevent columns from being autogenerated
Set the ColumnMapping property of the data source's DataColumn to Hidden.
// Assuming you have a DataTable with a column you want to exclude dataTable.Columns["SensitiveData"].ColumnMapping = MappingType.Hidden;
' Assuming you have a DataTable with a column you want to exclude dataTable.Columns("SensitiveData").ColumnMapping = MappingType.Hidden
Example
private void BindDataAndInitializeColumns()
{
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = customersDataSet;
dataGridView1.Columns.Remove("Fax");
dataGridView1.Columns["CustomerID"].Visible = false;
}
Private Sub BindDataAndInitializeColumns()
With dataGridView1
.AutoGenerateColumns = True
.DataSource = customersDataSet
.Columns.Remove("Fax")
.Columns("CustomerID").Visible = False
End With
End Sub
Compiling the Code
This example requires:
A DataGridView control named
dataGridView1
bound to a table that containsFax
andCustomerID
columns, such as theCustomers
table in the Northwind sample database.References to the System and System.Windows.Forms assemblies.
See also
.NET Desktop feedback