Creating Columns and Binding Them to Data Fields
- 2 minutes to read
When the DXGrid for Silverlight 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 data fields.
Automatically create columns for all fields in a data source
A grid automatically generates columns for all fields in a data source. The order of columns is the same as the order of fields in a data source. The grid's GridControl.Columns collection is populated at runtime. This collection is empty at design time.
This behavior is controlled by the DataControlBase.AutoPopulateColumns property. If this property is set to true and the grid's GridControl.Columns collection is empty, binding the grid to a data source automatically generates columns for all fields in a data source and adds them to the GridControl.Columns collection. After all columns have been created and added to the collection, the grid fires the DataControlBase.ColumnsPopulated event. Handle this event to customize auto-generated columns.
This can be useful, for example, when the structure of an underlying data source is unknown (e.g. switching between data tables).
Create columns and bind them to data fields manually
Manually create all the necessary columns, add them to the GridControl.Columns collection and bind them to data source fields using their ColumnBase.FieldName property.
#Creating and Binding Columns in XAML
The following code shows how to create columns in XAML.
<dxg:GridControl x:Name="grid">
<dxg:GridControl.Columns>
<dxg:GridColumn FieldName="ProductName"/>
<dxg:GridColumn FieldName="UnitPrice"/>
</dxg:GridControl.Columns>
<dxg:GridControl.View>
<dxg:TableView />
</dxg:GridControl.View>
</dxg:GridControl>
#Creating and Binding Columns at Runtime
The following example shows how to create a column and bind it to a data field.
using DevExpress.Xpf.Grid;
// ...
GridColumn column = new GridColumn();
column.FieldName = "ProductName";
grid.Columns.Add(column);
To create columns for all fields in a data source, call the DataControlBase.PopulateColumns method. This method clears a grid's GridControl.Columns collectio, and re-populates it with columns that correspond to all fields in a data source.