windowsforms-113894-controls-and-libraries-data-grid-getting-started-with-data-grid-and-views.md
The WinForms Data Grid (GridControl class) is a data-aware control that can display data in various formats (Views). This topic describes how to work with the Grid control, its Views and columns (data fields).
This video walks you through basic Data Grid customization. It begins with an empty Data Grid control with an applied GridView format, which displays records as rows and columns. Then, it shows the main Grid control features: data binding, column creation, sorting, grouping, and filtering data, summaries, access to grid options, in-place editors, etc. Finally, the GridView is converted to the LayoutView format, which displays underlying data as cards instead of rows and columns.
The WinForms Grid control ships with a flexible View-based architecture. Views — visual components that can be embedded in the Data Grid. Assign an appropriate View to the Grid control to display data in a specific manner.
The Grid control supports the following data views:
The GridView displays data in a tabular form. It is represented by the GridView class.
GridView - Standard Table View
GridView - Data Grouping
GridView - Conditional Formatting
GridView - Cell Merging
GridView - Row Auto Height
Features include:
The Banded GridView displays data in a tabular form and organizes columns into bands. It is represented by the BandedGridView class.
One Band Level - Row Auto Height
Nested Bands
Fixed Bands and Data Grouping
Features include:
Learn more about Banded GridView
The Advanced Banded GridView displays data in a tabular form, organizes columns into bands, and supports complex data cell arrangement. It is represented by the AdvBandedGridView class.
Multi-Row Cell Layout
Data Grouping
Customization Form
The main features of the Advanced Banded Grid View match those of the Grid View (except for Cell Merging). Features include:
Learn more about Advanced Banded GridView
The Layout View displays records as cards in one or more columns, in one or more rows, in an ellipse (carousel mode), or as a single card at a time. The view supports complex card field layouts, built-in groups, tabbed groups, and labels. It is represented by the LayoutView class.
LayoutView
LayoutView - Runtime Customization
LayoutView - Carousel Mode
Features include:
The Card View displays data records as cards, arranged down and then across. Card fields are always arranged in a single column. The Card View is represented by the CardView class.
CardView
CardView - Runtime Customization
Features include:
The WinExplorer View displays records using one of seven styles supported by Microsoft Windows Explorer — Small, Medium, Large, Extra Large, List, Tiles, and Content. The view supports HTML-CSS templates that allow you to create fully custom UIs. The view is represented by the WinExplorerView class.
WinExplorerView - Tiles Style
WinExplorerView - Small Style
WinExplorerView - Medium Style
WinExplorerView - Large Style
WinExplorerView - ExtraLarge Style
WinExplorerView - Content Style
WinExplorerView - List Style
Features include:
Learn more about WinExplorerView
The Tile View displays records as tiles using one of the following layout modes: default (standard table layout), list (tiles have no space between them), or Kanban. The Tile View includes the Tile Template feature that allows you to arrange fields relative to other fields, specify absolute or relative field display bounds, etc. In-place editors are supported when you use HTML-based templates.
The Tile View is represented by the TileView class.
Features include:
The Items View renders items (records) using an HTML-CSS template that you can specify with a property, or dynamically with an event. It is represented by the ItemsView class.
When you drop a GridControl onto the form at design time (or when you create this control in code), it is created with an embedded GridView - a View that presents underlying data as a two-dimensional table.
At design time :
At runtime (after you bind the grid to data and add columns to the GridView):
At design time, the data grid displays the Level Designer at the bottom right corner. The Level Designer allows you to access and manipulate (create, delete, and convert) data Views, and run the Grid Designer.
The box in the Level Designer identifies the current View. Click Change view to change the data View.
Select one of the following options:
For instance, if you convert the GridView to CardView, the Level Designer will display .
At runtime, you will see the following card UI:
Note
The Grid Control can also display data from hierarchical data sources (with two or more tables (data lists) linked by master-detail relationships). These relationships are also called one-to-many relationships: each record in a master table corresponds to one or more records in a child (detail) table. With the Level Designer, you can specify the data Views that display master and detail tables.
Read the following topic for detailed information: Master-Detail Relationships.
A View’s data is supplied by the grid control’s bound data source that is specified by the GridControl.DataSource and GridControl.DataMember properties.
At design time, you can use the Grid’s smart tag menu to bind the grid control to data.
You can do one of the following:
Important
The DevExpress Data Source Wizard calls the standard Visual Studio Data Source Configuration Wizard that is not available in .NET projects. You should create datasets, binding sources, and table adapters manually (or you can generate them in a .NET Framework project and add to the .NET project).
Important Notes Related to Design-Time Customization in .NET Apps
Refer to the following topic for more information: Data Binding.
Once you bind the grid control to data, the View automatically creates columns for all fields in the bound data source (if the grid’s column collection was empty before binding). The following image shows the GridView populated with data from a sample data table that has five data fields.
You can use the View’s OptionsBehavior.AutoPopulateColumns setting to disable automatic column population.
Unlike other Views, the WinExplorerView and TileView do not automatically show added columns. For these Views, additional customization is required to set up a layout within items/cards. Read the following topics for more information:
Views and their columns have multiple options and events to customize the way underlying data is presented on-screen. You can access and customize their settings in a number of ways.
Since View and column objects are visual components, they are accessible from the Visual Studio Properties window.
The data grid supports design-time on-form selection of Views and columns. To select a View and list its settings in the Properties window, click the View in the Level Designer.
To select a column, click its header directly on the form:
Column smart tags display main column settings in GridViews, Banded GridViews, and Advanced Banded GridViews:
The Grid Designer allows you to manage Views, columns, in-place editors, group summaries, appearance settings, and layout options. It contains the “Feature Browser” page to quickly locate settings related to a specific functionality. To invoke the Grid Designer, click the Run Designer button in the Level Designer:
The Grid Designer has a navigation bar on the left that allows you to select various pages. For instance, the Views page is equivalent to the Level Designer. This page allows you to access the current top level View and nested Views (if any).
The Columns page shows available data source fields and columns (visible and hidden) that are bound to these fields. You can customize individual columns, clear the column collection, add new columns manually, or populate the View with columns from the bound data source with a single button click.
The Feature Browser page categorizes options and events based on specific features:
Read the following topic for more information: Grid Designer.
View and column objects are components. When created at design time, you can access them in code by their names:
gridView1.OptionsBehavior.AutoPopulateColumns = false;
gridColumn1.VisibleIndex = -1;
GridView1.OptionsBehavior.AutoPopulateColumns = False
GridColumn1.VisibleIndex = -1
Use the GridControl.MainView property to access the grid control’s top level View (you should cast this property value to the corresponding View type):
GridView view = gridControl1.MainView as GridView;
if (view != null)
view.OptionsView.RowAutoHeight = true;
Dim view As GridView = CType(GridControl1.MainView, GridView)
If Not view Is Nothing Then view.OptionsView.RowAutoHeight = True
The following example changes the main View:
LayoutView lv = new LayoutView(gridControl1);
gridControl1.MainView = lv;
Dim lv As LayoutView = New LayoutView(GridControl1)
GridControl1.MainView = lv
You can obtain grid columns from the View’s ColumnView.Columns collection by the index or field name:
gridView1.Columns["ID"].Caption = "№";
GridView1.Columns("ID").Caption = "№"
In master-detail mode, the data grid displays multiple Views. Use the following properties and methods to get displayed detail Views:
Refer to the following help topics for more information: Master-Detail Relationships - Pattern and Clone Views and Access Master and Clone Views.
The following example replaces the existing top level View with a BandedGridView, and adds a band and column to the View:
using DevExpress.XtraGrid.Views.BandedGrid;
// Dispose of the old view
gridControl1.MainView.Dispose();
// Create a Banded Grid View
BandedGridView bandedView = new BandedGridView(gridControl1);
gridControl1.MainView = bandedView;
// Add one band and one column to the view
GridBand band = bandedView.Bands.AddBand("General");
BandedGridColumn column = (BandedGridColumn)bandedView.Columns.AddField("CustomerID");
column.OwnerBand = band;
column.Visible = true;
Imports DevExpress.XtraGrid.Views.BandedGrid
' Dispose of the old view
GridControl1.MainView.Dispose()
' Create a Banded Grid View
Dim bandedView As BandedGridView = New BandedGridView(GridControl1)
GridControl1.MainView = bandedView
' Add one band and one column to the view
Dim band As GridBand = bandedView.Bands.AddBand("General")
Dim column As BandedGridColumn = bandedView.Columns.AddField("CustomerID")
column.OwnerBand = band
column.Visible = True
The GridView, BandedGridView, and AdvBandedGridView support on-form design-time layout customization via drag-and-drop. You can re-order, resize and hide columns and bands:
The context menu, invoked on a column header click, allows you to sort and group data against a column, calculate the best column width and show the Column Chooser (Column/Band Chooser in Banded Views) - a floating panel that provides access to hidden columns (and bands in Banded Views). Hidden columns (and bands) can be restored from the Column/Band Chooser back to the View using drag-and-drop:
You can also customize column and band settings in the Visual Studio Properties window (GridColumn.VisibleIndex, GridBand.VisibleIndex, GridColumn.Width, GridColumn.SortOrder, GridColumn.SortIndex, etc.).
For Banded Views (BandedGridView and AdvBandedGridView), use the Bands page of the Grid Designer to add new bands and rearrange bands and columns. You can also re-arrange bands and columns on the form:
The following example creates a GridControl at runtime and shows how to perform basic customization tasks:
Note
Add the corresponding assemblies to your Windows Forms project.
Read the following topic for information: Redistribution and Deployment of .NET Framework Apps.
using System;
using DevExpress.ClipboardSource.SpreadsheetML;
using DevExpress.Data;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Runtime.CompilerServices;
using System.Windows.Forms;
namespace DXApplication {
public partial class Form1 : XtraForm {
public Form1() {
InitializeComponent();
this.Load += Form1_Load;
}
private void Form1_Load(object sender, EventArgs e) {
GridControl gridControl1 = new GridControl() {
Name = "gridControl1",
Parent = this,
Dock = DockStyle.Fill
};
gridControl1.DataSource = DataHelper.GetData(30);
// The grid automatically creates columns for the public fields found in the data source.
// Calling the gridView1.PopulateColumns method is not required unless gridView1.OptionsBehavior.AutoPopulateColumns is disabled.
// The grid automatically creates a GridView that displays the underlying data as a two-dimensional table.
GridView gridView1 = gridControl1.MainView as GridView;
// Obtain created columns.
GridColumn colCompany = gridView1.Columns["CompanyName"];
GridColumn colID = gridView1.Columns["ID"];
GridColumn colDate = gridView1.Columns["RequiredDate"];
GridColumn colPayment = gridView1.Columns["Value"];
GridColumn colProcessed = gridView1.Columns["Processed"];
// The Company column uses a ComboBox in-place editor that shows a list of available companies.
RepositoryItemComboBox riComboBox = new RepositoryItemComboBox();
riComboBox.Items.AddRange(DataHelper.companies);
gridControl1.RepositoryItems.Add(riComboBox);
colCompany.ColumnEdit = riComboBox;
// Hide a column.
colID.Visible = false;
// Group and sort data.
colCompany.GroupIndex = 0;
colDate.SortIndex = 0;
colDate.SortOrder = DevExpress.Data.ColumnSortOrder.Descending;
// Show group columns in the table.
gridView1.OptionsView.ShowGroupedColumns = true;
// Expand group rows.
gridView1.ExpandAllGroups();
// Apply a filter.
gridView1.ActiveFilterString = "[RequiredDate]>= #" + DateTime.Today.ToString() + "#";
// Calculate two total summaries.
colDate.Summary.Add(SummaryItemType.Count, colDate.FieldName, "Count={0}");
colDate.Summary.Add(SummaryItemType.Max, colDate.FieldName, "Max={0:d}");
gridView1.OptionsView.ShowFooter = true;
// Calculate group summaries.
GridGroupSummaryItem item = new GridGroupSummaryItem();
item.FieldName = colCompany.FieldName;
item.SummaryType = DevExpress.Data.SummaryItemType.Count;
gridView1.GroupSummary.Add(item);
GridGroupSummaryItem item1 = new GridGroupSummaryItem();
item1.FieldName = colPayment.FieldName;
item1.SummaryType = SummaryItemType.Sum;
item1.DisplayFormat = "group total={0:c2}";
item1.ShowInGroupColumnFooter = colPayment;
gridView1.GroupSummary.Add(item1);
// Forcibly move group footer summaries to positions in group rows under corresponding column headers.
gridView1.OptionsBehavior.AlignGroupSummaryInGroupRow = DevExpress.Utils.DefaultBoolean.True;
// Focus a specific cell.
gridView1.FocusedRowHandle = 1;
gridView1.FocusedColumn = colCompany;
// Optimize column widths.
colDate.BestFit();
colProcessed.BestFit();
}
}
public class Record : INotifyPropertyChanged {
public Record() {
}
int id;
public int ID {
get { return id; }
set {
if(id != value) {
id = value;
OnPropertyChanged();
}
}
}
string text;
[DisplayName("Company")]
public string CompanyName {
get { return text; }
set {
if(text != value) {
if(string.IsNullOrEmpty(value))
throw new Exception();
text = value;
OnPropertyChanged();
}
}
}
Nullable<decimal> val;
[DataType(System.ComponentModel.DataAnnotations.DataType.Currency)]
[DisplayName("Payment")]
public Nullable<decimal> Value {
get { return val; }
set {
if(val != value) {
val = value;
OnPropertyChanged();
}
}
}
DateTime dt;
[DisplayFormat(DataFormatString = "d")]
public DateTime RequiredDate {
get { return dt; }
set {
if(dt != value) {
dt = value;
OnPropertyChanged();
}
}
}
bool state;
public bool Processed {
get { return state; }
set {
if(state != value) {
state = value;
OnPropertyChanged();
}
}
}
public override string ToString() {
return string.Format("ID = {0}, Text = {1}", ID, CompanyName);
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = "") {
if(PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public class DataHelper {
public static string[] companies = new string[] { "Hanari Carnes", "Que Delícia", "Romero y tomillo", "Mère Paillarde",
"Comércio Mineiro", "Reggiani Caseifici", "Maison Dewey" };
public static BindingList<Record> GetData(int count) {
BindingList<Record> records = new BindingList<Record>();
Random rnd = new Random();
for(int i = 0; i < count; i++) {
int n = rnd.Next(10);
records.Add(new Record() {
ID = i + 100,
CompanyName = companies[i % companies.Length],
RequiredDate = DateTime.Today.AddDays(n - 5),
Value = i % 2 == 0 ? (i + 1) * 123 : i * 231,
Processed = i % 2 == 0,
});
};
return records;
}
}
}
Imports System
Imports DevExpress.ClipboardSource.SpreadsheetML
Imports DevExpress.Data
Imports DevExpress.XtraEditors
Imports DevExpress.XtraEditors.Repository
Imports DevExpress.XtraGrid
Imports DevExpress.XtraGrid.Columns
Imports DevExpress.XtraGrid.Views.Grid
Imports System.ComponentModel
Imports System.ComponentModel.DataAnnotations
Imports System.Runtime.CompilerServices
Imports System.Windows.Forms
Namespace DXApplication
Partial Public Class Form1
Inherits XtraForm
Public Sub New()
InitializeComponent()
AddHandler Me.Load, AddressOf Form1_Load
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim gridControl1 As New GridControl() With {.Name = "gridControl1", .Parent = Me, .Dock = DockStyle.Fill}
gridControl1.DataSource = DataHelper.GetData(30)
' The grid automatically creates columns for the public fields found in the data source.
' Calling the gridView1.PopulateColumns method is not required unless gridView1.OptionsBehavior.AutoPopulateColumns is disabled.
' The grid automatically creates a GridView that displays the underlying data as a two-dimensional table.
Dim gridView1 As GridView = TryCast(gridControl1.MainView, GridView)
' Obtain created columns.
Dim colCompany As GridColumn = gridView1.Columns("CompanyName")
Dim colID As GridColumn = gridView1.Columns("ID")
Dim colDate As GridColumn = gridView1.Columns("RequiredDate")
Dim colPayment As GridColumn = gridView1.Columns("Value")
Dim colProcessed As GridColumn = gridView1.Columns("Processed")
' The Company column uses a ComboBox in-place editor that shows a list of available companies.
Dim riComboBox As New RepositoryItemComboBox()
riComboBox.Items.AddRange(DataHelper.companies)
gridControl1.RepositoryItems.Add(riComboBox)
colCompany.ColumnEdit = riComboBox
' Hide a column.
colID.Visible = False
' Group and sort data.
colCompany.GroupIndex = 0
colDate.SortIndex = 0
colDate.SortOrder = DevExpress.Data.ColumnSortOrder.Descending
' Show group columns in the table.
gridView1.OptionsView.ShowGroupedColumns = True
' Expand group rows.
gridView1.ExpandAllGroups()
' Apply a filter.
gridView1.ActiveFilterString = "[RequiredDate]>= #" & Date.Today.ToString() & "#"
' Calculate two total summaries.
colDate.Summary.Add(SummaryItemType.Count, colDate.FieldName, "Count={0}")
colDate.Summary.Add(SummaryItemType.Max, colDate.FieldName, "Max={0:d}")
gridView1.OptionsView.ShowFooter = True
' Calculate group summaries.
Dim item As New GridGroupSummaryItem()
item.FieldName = colCompany.FieldName
item.SummaryType = DevExpress.Data.SummaryItemType.Count
gridView1.GroupSummary.Add(item)
Dim item1 As New GridGroupSummaryItem()
item1.FieldName = colPayment.FieldName
item1.SummaryType = SummaryItemType.Sum
item1.DisplayFormat = "group total={0:c2}"
item1.ShowInGroupColumnFooter = colPayment
gridView1.GroupSummary.Add(item1)
' Forcibly move group footer summaries to positions in group rows under corresponding column headers.
gridView1.OptionsBehavior.AlignGroupSummaryInGroupRow = DevExpress.Utils.DefaultBoolean.True
' Focus a specific cell.
gridView1.FocusedRowHandle = 1
gridView1.FocusedColumn = colCompany
' Optimize column widths.
colDate.BestFit()
colProcessed.BestFit()
End Sub
End Class
Public Class Record
Implements INotifyPropertyChanged
Public Sub New()
End Sub
Private id_Renamed As Integer
Public Property ID() As Integer
Get
Return id_Renamed
End Get
Set(ByVal value As Integer)
If id_Renamed <> value Then
id_Renamed = value
OnPropertyChanged()
End If
End Set
End Property
Private text As String
<DisplayName("Company")>
Public Property CompanyName() As String
Get
Return text
End Get
Set(ByVal value As String)
If text <> value Then
If String.IsNullOrEmpty(value) Then
Throw New Exception()
End If
text = value
OnPropertyChanged()
End If
End Set
End Property
Private val? As Decimal
<DataType(System.ComponentModel.DataAnnotations.DataType.Currency), DisplayName("Payment")>
Public Property Value() As Decimal?
Get
Return val
End Get
Set(ByVal value? As Decimal)
If Not val.Equals(value) Then
val = value
OnPropertyChanged()
End If
End Set
End Property
Private dt As Date
<DisplayFormat(DataFormatString := "d")>
Public Property RequiredDate() As Date
Get
Return dt
End Get
Set(ByVal value As Date)
If dt <> value Then
dt = value
OnPropertyChanged()
End If
End Set
End Property
Private state As Boolean
Public Property Processed() As Boolean
Get
Return state
End Get
Set(ByVal value As Boolean)
If state <> value Then
state = value
OnPropertyChanged()
End If
End Set
End Property
Public Overrides Function ToString() As String
Return String.Format("ID = {0}, Text = {1}", ID, CompanyName)
End Function
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Protected Sub OnPropertyChanged(Optional <CallerMemberName> ByVal propertyName As String = "")
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub
End Class
Public Class DataHelper
Public Shared companies() As String = { "Hanari Carnes", "Que Delícia", "Romero y tomillo", "Mère Paillarde", "Comércio Mineiro", "Reggiani Caseifici", "Maison Dewey" }
Public Shared Function GetData(ByVal count As Integer) As BindingList(Of Record)
Dim records As New BindingList(Of Record)()
Dim rnd As New Random()
For i As Integer = 0 To count - 1
Dim n As Integer = rnd.Next(10)
records.Add(New Record() With {.ID = i + 100, .CompanyName = companies(i Mod companies.Length), .RequiredDate = Date.Today.AddDays(n - 5), .Value = If(i Mod 2 = 0, (i + 1) * 123, i * 231), .Processed = i Mod 2 = 0})
Next i
Return records
End Function
End Class
End Namespace
This example shows how to create a GridControl, while presenting its underlying data using a banded grid format (BandedGridView). The example creates three bands (Main, Address and Phone), adds columns to the bands and customizes the background color for the third band and its columns.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.BandedGrid;
namespace DXApplication {
public partial class Form1 : XtraForm {
public Form1() {
InitializeComponent();
this.Load += Form1_Load;
}
private void Form1_Load(object sender, EventArgs e) {
GridControl gridControl1 = new GridControl() { Parent = this, Dock = DockStyle.Fill };
BandedGridView bandedGridView1 = new BandedGridView(gridControl1);
GridBand gridBandMain = new GridBand() { Caption = "Main", VisibleIndex = 0 };
GridBand gridBandAddress = new GridBand() { Caption = "Address", VisibleIndex = 1 };
GridBand gridBandPhone = new GridBand() { Caption = "Phone", VisibleIndex = 2 };
BandedGridColumn colCity = new BandedGridColumn() { FieldName = "City", Visible = true };
BandedGridColumn colCompanyName = new BandedGridColumn() { FieldName = "CompanyName", Visible = true };
BandedGridColumn colContactName = new BandedGridColumn() { FieldName = "ContactName", Visible = true };
BandedGridColumn colCountry = new BandedGridColumn() { FieldName = "Country", Visible = true };
BandedGridColumn colPhone = new BandedGridColumn() { FieldName = "Phone", Visible = true };
BandedGridColumn colFax = new BandedGridColumn() { FieldName = "Fax", Visible = true };
gridControl1.DataSource = new List<DataRecord>() {
new DataRecord(){ City = "LA", CompanyName = "My Company", ContactName = "John White",
Country = "USA", Fax = "555-2211", Phone = "555-2212" }
};
gridControl1.ViewCollection.Add(bandedGridView1);
gridControl1.MainView = bandedGridView1;
bandedGridView1.Bands.AddRange(new GridBand[] { gridBandMain, gridBandAddress, gridBandPhone });
bandedGridView1.Columns.AddRange(new BandedGridColumn[] { colCompanyName, colContactName, colCity, colCountry, colPhone, colFax });
colPhone.AppearanceCell.BackColor = System.Drawing.Color.PowderBlue;
colPhone.AppearanceCell.Options.UseBackColor = true;
colPhone.AppearanceHeader.BackColor = System.Drawing.Color.PowderBlue;
colPhone.AppearanceHeader.Options.UseBackColor = true;
colFax.AppearanceCell.BackColor = System.Drawing.Color.PowderBlue;
colFax.AppearanceCell.Options.UseBackColor = true;
colFax.AppearanceHeader.BackColor = System.Drawing.Color.PowderBlue;
colFax.AppearanceHeader.Options.UseBackColor = true;
gridBandMain.Columns.Add(colCompanyName);
gridBandMain.Columns.Add(colContactName);
gridBandAddress.Columns.Add(colCountry);
gridBandAddress.Columns.Add(colCity);
gridBandPhone.AppearanceHeader.BackColor = System.Drawing.Color.LightBlue;
gridBandPhone.AppearanceHeader.Options.UseBackColor = true;
gridBandPhone.Columns.Add(colPhone);
gridBandPhone.Columns.Add(colFax);
bandedGridView1.OptionsCustomization.AllowChangeColumnParent = false;
}
}
public class DataRecord {
public string CompanyName{ get; set; }
public string ContactName { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
}
}
Imports System
Imports System.Collections.Generic
Imports System.Windows.Forms
Imports DevExpress.XtraEditors
Imports DevExpress.XtraGrid
Imports DevExpress.XtraGrid.Views.BandedGrid
Namespace DXApplication
Partial Public Class Form1
Inherits XtraForm
Public Sub New()
InitializeComponent()
AddHandler Me.Load, AddressOf Form1_Load
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim gridControl1 As New GridControl() With {
.Parent = Me,
.Dock = DockStyle.Fill
}
Dim bandedGridView1 As New BandedGridView(gridControl1)
Dim gridBandMain As New GridBand() With {
.Caption = "Main",
.VisibleIndex = 0
}
Dim gridBandAddress As New GridBand() With {
.Caption = "Address",
.VisibleIndex = 1
}
Dim gridBandPhone As New GridBand() With {
.Caption = "Phone",
.VisibleIndex = 2
}
Dim colCity As New BandedGridColumn() With {
.FieldName = "City",
.Visible = True
}
Dim colCompanyName As New BandedGridColumn() With {
.FieldName = "CompanyName",
.Visible = True
}
Dim colContactName As New BandedGridColumn() With {
.FieldName = "ContactName",
.Visible = True
}
Dim colCountry As New BandedGridColumn() With {
.FieldName = "Country",
.Visible = True
}
Dim colPhone As New BandedGridColumn() With {
.FieldName = "Phone",
.Visible = True
}
Dim colFax As New BandedGridColumn() With {
.FieldName = "Fax",
.Visible = True
}
gridControl1.DataSource = New List(Of DataRecord)() From {
New DataRecord() With {
.City = "LA",
.CompanyName = "My Company",
.ContactName = "John White",
.Country = "USA",
.Fax = "555-2211",
.Phone = "555-2212"
}
}
gridControl1.ViewCollection.Add(bandedGridView1)
gridControl1.MainView = bandedGridView1
bandedGridView1.Bands.AddRange(New GridBand() { gridBandMain, gridBandAddress, gridBandPhone })
bandedGridView1.Columns.AddRange(New BandedGridColumn() { colCompanyName, colContactName, colCity, colCountry, colPhone, colFax })
colPhone.AppearanceCell.BackColor = System.Drawing.Color.PowderBlue
colPhone.AppearanceCell.Options.UseBackColor = True
colPhone.AppearanceHeader.BackColor = System.Drawing.Color.PowderBlue
colPhone.AppearanceHeader.Options.UseBackColor = True
colFax.AppearanceCell.BackColor = System.Drawing.Color.PowderBlue
colFax.AppearanceCell.Options.UseBackColor = True
colFax.AppearanceHeader.BackColor = System.Drawing.Color.PowderBlue
colFax.AppearanceHeader.Options.UseBackColor = True
gridBandMain.Columns.Add(colCompanyName)
gridBandMain.Columns.Add(colContactName)
gridBandAddress.Columns.Add(colCountry)
gridBandAddress.Columns.Add(colCity)
gridBandPhone.AppearanceHeader.BackColor = System.Drawing.Color.LightBlue
gridBandPhone.AppearanceHeader.Options.UseBackColor = True
gridBandPhone.Columns.Add(colPhone)
gridBandPhone.Columns.Add(colFax)
bandedGridView1.OptionsCustomization.AllowChangeColumnParent = False
End Sub
End Class
Public Class DataRecord
Public Property CompanyName() As String
Public Property ContactName() As String
Public Property City() As String
Public Property Country() As String
Public Property Phone() As String
Public Property Fax() As String
End Class
End Namespace
The following example shows how to create and customize a Layout View in code. In the example, a template card is created, consisting of six fields arranged as in the image below:
Before arranging layout fields in code, ensure that corresponding columns are visible (see LayoutViewColumn.Visible and GridColumnCollection.AddVisible).
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Layout;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraLayout;
using DevExpress.XtraLayout.Customization;
using DevExpress.XtraLayout.Utils;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraEditors.Controls;
GridControl grid = new GridControl();
LayoutView lView = new LayoutView(grid);
grid.MainView = lView;
lView.OptionsBehavior.AutoPopulateColumns = false;
grid.DataSource = employeesBindingSource;
this.Controls.Add(grid);
grid.Dock = DockStyle.Fill;
// Create columns.
LayoutViewColumn colFirstName = lView.Columns.AddVisible("FirstName") as LayoutViewColumn;
LayoutViewColumn colLastName = lView.Columns.AddVisible("LastName") as LayoutViewColumn;
LayoutViewColumn colAddress = lView.Columns.AddVisible("Address") as LayoutViewColumn;
LayoutViewColumn colCity = lView.Columns.AddVisible("City") as LayoutViewColumn;
LayoutViewColumn colCountry = lView.Columns.AddVisible("Country") as LayoutViewColumn;
LayoutViewColumn colPhoto = lView.Columns.AddVisible("Photo") as LayoutViewColumn;
// Access corresponding card fields.
LayoutViewField fieldFirstName = colFirstName.LayoutViewField;
LayoutViewField fieldLastName = colLastName.LayoutViewField;
LayoutViewField fieldAddress = colAddress.LayoutViewField;
LayoutViewField fieldCity = colCity.LayoutViewField;
LayoutViewField fieldCountry = colCountry.LayoutViewField;
LayoutViewField fieldPhoto = colPhoto.LayoutViewField;
// Position the FirstName field to the right of the Photo field.
fieldFirstName.Move(new LayoutItemDragController(fieldFirstName, fieldPhoto,
InsertLocation.After, LayoutType.Horizontal));
// Position the LastName field below the FirstName field.
fieldLastName.Move(new LayoutItemDragController(fieldLastName, fieldFirstName,
InsertLocation.After, LayoutType.Vertical));
// Create an Address Info group.
LayoutControlGroup groupAddress = new LayoutControlGroup();
groupAddress.Text = "Address Info";
groupAddress.Name = "addressInfoGroup";
// Move the Address, City and Country fields to this group.
groupAddress.AddItem(fieldAddress);
fieldCity.Move(fieldAddress, InsertType.Bottom);
fieldCountry.Move(fieldCity, InsertType.Bottom);
lView.TemplateCard.AddGroup(groupAddress, fieldLastName, InsertType.Bottom);
// Assign editors to card fields.
RepositoryItemPictureEdit riPictureEdit = grid.RepositoryItems.Add("PictureEdit") as RepositoryItemPictureEdit;
riPictureEdit.SizeMode = PictureSizeMode.Squeeze;
colPhoto.ColumnEdit = riPictureEdit;
// Customize card field options.
colFirstName.Caption = "First Name";
colLastName.Caption = "Last Name";
// Set the card's minimum size.
lView.CardMinSize = new Size(250, 180);
fieldPhoto.TextVisible = false;
fieldPhoto.SizeConstraintsType = SizeConstraintsType.Custom;
fieldPhoto.MaxSize = fieldPhoto.MinSize = new Size(150, 150);
Imports DevExpress.XtraEditors.Controls
Imports DevExpress.XtraEditors.Repository
Imports DevExpress.XtraGrid
Imports DevExpress.XtraGrid.Columns
Imports DevExpress.XtraGrid.Views.Layout
Imports DevExpress.XtraLayout
Imports DevExpress.XtraLayout.Customization
Imports DevExpress.XtraLayout.Utils
Dim grid As GridControl = New GridControl()
Dim lView As LayoutView = New LayoutView(grid)
grid.MainView = lView
lView.OptionsBehavior.AutoPopulateColumns = False
grid.DataSource = employeesBindingSource
Me.Controls.Add(grid)
grid.Dock = DockStyle.Fill
' Create columns.
Dim colFirstName As LayoutViewColumn = TryCast(lView.Columns.AddVisible("FirstName"), LayoutViewColumn)
Dim colLastName As LayoutViewColumn = TryCast(lView.Columns.AddVisible("LastName"), LayoutViewColumn)
Dim colAddress As LayoutViewColumn = TryCast(lView.Columns.AddVisible("Address"), LayoutViewColumn)
Dim colCity As LayoutViewColumn = TryCast(lView.Columns.AddVisible("City"), LayoutViewColumn)
Dim colCountry As LayoutViewColumn = TryCast(lView.Columns.AddVisible("Country"), LayoutViewColumn)
Dim colPhoto As LayoutViewColumn = TryCast(lView.Columns.AddVisible("Photo"), LayoutViewColumn)
' Access corresponding card fields.
Dim fieldFirstName As LayoutViewField = colFirstName.LayoutViewField
Dim fieldLastName As LayoutViewField = colLastName.LayoutViewField
Dim fieldAddress As LayoutViewField = colAddress.LayoutViewField
Dim fieldCity As LayoutViewField = colCity.LayoutViewField
Dim fieldCountry As LayoutViewField = colCountry.LayoutViewField
Dim fieldPhoto As LayoutViewField = colPhoto.LayoutViewField
' Position the FirstName field to the right of the Photo field.
fieldFirstName.Move(New LayoutItemDragController(fieldFirstName, fieldPhoto, InsertLocation.After, LayoutType.Horizontal))
' Position the LastName field below the FirstName field.
fieldLastName.Move(New LayoutItemDragController(fieldLastName, fieldFirstName, InsertLocation.After, LayoutType.Vertical))
' Create an Address Info group.
Dim groupAddress As LayoutControlGroup = New LayoutControlGroup()
groupAddress.Text = "Address Info"
groupAddress.Name = "addressInfoGroup"
groupAddress.AddItem(fieldAddress)
' Move the Address, City and Country fields to this group.
fieldCity.Move(fieldAddress, InsertType.Bottom)
fieldCountry.Move(fieldCity, InsertType.Bottom)
lView.TemplateCard.AddGroup(groupAddress, fieldLastName, InsertType.Bottom)
' Assign editors to card fields.
Dim riPictureEdit As RepositoryItemPictureEdit = TryCast(grid.RepositoryItems.Add("PictureEdit"), RepositoryItemPictureEdit)
riPictureEdit.SizeMode = PictureSizeMode.Squeeze
colPhoto.ColumnEdit = riPictureEdit
' Customize card field options
colFirstName.Caption = "First Name"
colLastName.Caption = "Last Name"
' Set the card's minimum size.
lView.CardMinSize = New Size(350, 200)
fieldPhoto.TextVisible = False
fieldPhoto.SizeConstraintsType = SizeConstraintsType.Custom
fieldPhoto.MaxSize = New Size(150, 150)
fieldPhoto.MinSize = fieldPhoto.MaxSize