How to: Autogenerate Columns in a Data-Bound Windows Forms DataGridView Control

The following code example demonstrates how to display columns from a bound data source in a DataGridView control. When the AutoGenerateColumns property value is true (the default), a DataGridViewColumn is created for each column in the data source table.

If the DataGridView control already has columns when you set the DataSource property, the existing bound columns are compared to the columns in the data source and preserved whenever there is a match. Unbound columns are always preserved. Bound columns for which there is no match in the data source are removed. Columns in the data source for which there is no match in the control generate new DataGridViewColumn objects, which are added to the end of the Columns collection.

Example

Private Sub BindData()

    With customersDataGridView
        .AutoGenerateColumns = True
        .DataSource = customersDataSet
        .DataMember = "Customers"
    End With

End Sub
private void BindData()
{
    customersDataGridView.AutoGenerateColumns = true;
    customersDataGridView.DataSource = customersDataSet;
    customersDataGridView.DataMember = "Customers";
}

Compiling the Code

This example requires:

See Also

Tasks

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

Reference

DataGridView
System.Windows.Forms.DataGridView.AutoGenerateColumns

Other Resources

Displaying Data in the Windows Forms DataGridView Control