Skip to main content

Creating Columns and Binding Them to Data Fields

  • 2 minutes to read

When ASPxGridView is bound to a data source, you need to create columns and bind them to data fields. There are two ways to add columns and bind them to fields:

  • Automatically create columns for all data fields (default behavior).

    The ASPxGridView control automatically generates columns for all fields in the data source. The order of columns is the same as the order of fields in the data source. The ASPxGridView’s ASPxGridView.Columns collection is populated at runtime. This collection is empty at design time.

    This behavior is controlled by the ASPxGridView.AutoGenerateColumns property. This can be useful when the structure of the underlying data source is unknown (for example, when the grid switches between data tables).

  • Create columns and bind them to data fields manually.

    Switch the ASPxGridView.AutoGenerateColumns option off. In this instance, you should manually create all the necessary columns, add them to the ASPxGridView.Columns collection and bind them to data source fields using their GridViewDataColumn.FieldName property.

Creating and Binding Columns at Design Time

Invoke the Columns edit form to access the ASPxGridView’s column collection.

cdCreatingColumnsDT

This form allows you to add and delete columns, access and customize column settings, and perform other common collection management tasks.

You can also change the column’s type. To do this, right-click the required column to invoke the context menu. Select the ‘Change Column Type To’ menu item, and select the required column type.

ColumnType

Note

You can change the column’s type only at design time.

Creating and Binding Columns at Runtime

The example below shows how to create a data column.

using DevExpress.Web.ASPxGridView;

private void CreateGridColumn(ASPxGridView grid, string fieldName, string caption) {
    if (grid.Columns[caption] != null) return;
    GridViewDataColumn col = new GridViewDataColumn(fieldName, caption);
    grid.Columns.Add(col);
}

If grid columns are generated automatically (the ASPxGridView.AutoGenerateColumns option is enabled), you can add new columns within the grid’s DataBound event handler:

protected void ASPxGridView1_DataBound(object sender, EventArgs e) {
    if (ASPxGridView1.Columns["Command"] == null) {
        GridViewCommandColumn cmdCol = new GridViewCommandColumn("Command");
        cmdCol.EditButton.Visible = true;
        cmdCol.DeleteButton.Visible = true;
        ASPxGridView1.Columns.Add(cmdCol);
    }
}