GridViewExtension Class

A Grid View extension.

Namespace: DevExpress.Web.Mvc

Assembly: DevExpress.Web.Mvc5.v20.2.dll

Declaration

public class GridViewExtension :
    GridExtensionBase
Public Class GridViewExtension
    Inherits GridExtensionBase

Remarks

The GridViewExtension is a data bound extension that displays data from a data source in grid format. The grid displays data source fields and records as columns and rows in a table.

Add an Extension to View

Call the ExtensionsFactory.GridView helper method with the GridViewSettings object as a parameter to add the Grid View extension to a view.

@Html.DevExpress().GridView(settings =>{
    settings.Name = "myGridView";
    settings.CallbackRouteValues = new { Controller = "Home", Action = "GridViewPart" };
    settings.Width = 450;
    ...
    settings.Columns.Add("ContactName");
    settings.Columns.Add("CompanyName");
    settings.Columns.Add("City").SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;
    settings.Columns.Add("Region");
    settings.Columns.Add("Country");
}).Bind(Model).GetHtml()

Client-Side API

Availability

Available by default.

Client object type

ASPxClientGridView

Access name

ASPxGridView.ClientInstanceName

Events

ASPxGridView.ClientSideEvents

Concepts

GridView Overview

Features

Data Binding

The extension works only in bound mode. You can bind the grid to any standard data source type: SqlDataSource, ObjectDataSource, XmlDataSource, AccessDataSource, and SiteMapDataSource.

Use the KeyFieldName property to set a data source's key field name. The extension's Bind, BindToCustomData, BindToEF, BindToLINQ, and BindToXML methods allow you to bind the extension to data.

DataTable:

// Model
public static DataTable GetDataTableModel() {
    DataTable dataTable = new DataTable();

    dataTable.Columns.Add("ID", typeof(int));
    dataTable.Columns.Add("Text", typeof(string));
    //other columns

    dataTable.PrimaryKey = new DataColumn[] { dataTable.Columns["ID"] };

    // Specify data

    return dataTable;

// Controller
public ActionResult DataTableDataBinding() {
    if(Session["DataTableModel"] == null)
        Session["DataTableModel"] = InMemoryModel.GetDataTableModel();

    return View(Session["DataTableModel"]);
}
public ActionResult DataTableDataBindingPartial() {
    return PartialView(Session["DataTableModel"]);
}

// View
@Html.DevExpress().GridView(settings => {
    settings.Name = "myGridView";
    settings.CallbackRouteValues = new { Controller = "Home", Action = "DataTableDataBindingPartial" };

    settings.KeyFieldName = "ID";

    settings.Columns.Add("ID");
    settings.Columns.Add("Text");
    settings.Columns.Add("Quantity");
    settings.Columns.Add("Price");

}).Bind(Model).GetHtml()

See Also: How to bind GridView with standard in-memory data sources (DataTable, List)

Learn more | See demo

Database Server Mode

The grid supports database server mode. In this mode, the grid loads only required items to the server memory and implements data-aware operations (for example, filtering) at the database level.

// Model
public static class LargeDatabaseDataProvider {
    const string LargeDatabaseDataContextKey = "DXLargeDatabaseDataContext";
    public static LargeDatabaseContext DB {
        get {
            if(HttpContext.Current.Items[LargeDatabaseDataContextKey] == null)
                HttpContext.Current.Items[LargeDatabaseDataContextKey] = new LargeDatabaseContext();
            return (LargeDatabaseContext)HttpContext.Current.Items[LargeDatabaseDataContextKey];
        }
    }
    //...
}
// View
@Html.DevExpress().GridView(settings => {
    settings.Name = "myGridView";
    settings.CallbackRouteValues = new { Controller = "DataBinding", Action = "DataBindingToLargeDatabasePartial" };

    settings.KeyFieldName = "ID";

    //...
}).BindToEF(string.Empty, string.Empty, (s, e) => {
    e.QueryableSource = LargeDatabaseDataProvider.DB.Emails;
}).GetHtml()

Learn more | See demo

Unbound Columns

The grid extension supports unbound columns that are not bound to any data source field. Use the CustomUnboundColumnData or the UnboundExpression properties to populate an unbound column with data.

@Html.DevExpress().GridView(settings => {
    settings.Name = "myGridView";
    //...
    settings.Columns.Add(unboundColumn => {
        unboundColumn.FieldName = "UniqueFieldName";
        unboundColumn.UnboundType = DevExpress.Data.UnboundColumnType.Decimal;
    });

    settings.CustomUnboundColumnData = (sender, e) => {
        if (e.Column.FieldName == "UniqueFieldName") {
            int quantity = Convert.ToInt32(e.GetListSourceFieldValue("Quantity"));
            decimal price = (decimal)e.GetListSourceFieldValue("Price");

            e.Value = quantity * price;
        }
    };
}).Bind(Model).GetHtml()

Learn more

Columns Management

The grid extension displays data in a table format. Data sources provide data as fields and records. The grid extension displays data fields as columns and records - as data rows.

Learn more

Resize Columns

You can resize a column header to modify the column's width (SettingsResizing).

settings.SettingsResizing.ColumnResizeMode = ColumnResizeMode.Control;

See demo

Move Columns

The grid extension supports drag-and-drop functionality that allows you to move a column to the desired position among other columns. You can use the AllowDragDrop property to allow end users to move all grid columns or a column's Settings.AllowDragDrop property to enable drag and drop for an individual column.

// Control's setting
settings.SettingsBehavior.AllowDragDrop = false;

// Column's setting
settings.Columns.Add(column => {
    column.Settings.AllowDragDrop = DefaultBoolean.False;
});

See demo

Header and Data Cell Bands

The grid extension enables you to organize columns in logical groups (bands) and display them in multiple rows. Header bands (MVCxGridViewBandColumn) organize grid columns into logical groups and display hierarchical multi-row headers.

// Parent header band
settings.Columns.AddBand(orderBand => {
    orderBand.Caption = "Order";
    // Child header band
    orderBand.Columns.AddBand(companyBand => {
        companyBand.Caption = "Company";
        // The 'Company' header band's child data columns
        companyBand.Columns.Add("CompanyName");
        companyBand.Columns.Add("Country");
    });
    // Child data column
    orderBand.Columns.Add("TotalSum");
});

Learn more | See demo

Data cell bands (Columns) allow you to display a data record hierarchically.

settings.Columns.Add(address => {
    address.FieldName = "Address";
    address.Columns.Add("Price");
    address.Columns.Add(features => {
        features.FieldName = "Features";
        features.Columns.Add("Beds");
        features.Columns.Add("Baths");
        features.Columns.Add("HouseSize");
    });
});

Learn more | See demo

Fixed Columns

The grid allows you to fix columns on the left side and display these columns onscreen when the columns' total width exceeds the grid width. Enable the horizontal scrolling (HorizontalScrollBarMode) and set a column's FixedStyle property to Left to fix the column.

settings.Columns.Add(column => {
    column.FieldName = "ContactName";
    column.Width = 150;
    column.FixedStyle = GridViewColumnFixedStyle.Left;
});

Learn more | See demo

Truncate Cell Text

The grid can truncate cell ('...') values if they don't fit the cells width ( AllowEllipsisInText).

settings.SettingsBehavior.AllowEllipsisInText = true;

See demo

Data Editing

Edit Modes

The grid provides the following built-in edit modes that allow end-users to edit grid data (Mode):

  • Edit Form (See demo)
  • Edit Form and Display Row
  • Popup Edit Form
  • In-Line Edit Mode
  • Batch - (See demo)
settings.SettingsEditing.Mode = GridViewEditingMode.Batch;

Learn more | See demo

Edit Form Template

You can use any extensions to create a custom layout for the edit form.

settings.SetEditFormTemplateContent(c => {
    Html.DevExpress().FormLayout(flSettings => {
      //...
    })
});

See demo

Edit Form Layout

The EditFormLayoutProperties property allows you to customize the edit form layout.

settings.EditFormLayoutProperties.ColCount = 2;
settings.EditFormLayoutProperties.AlignItemCaptionsInAllGroups = true;
settings.EditFormLayoutProperties.SettingsAdaptivity.AdaptivityMode = FormLayoutAdaptivityMode.SingleColumnWindowLimit;
settings.EditFormLayoutProperties.SettingsAdaptivity.SwitchToSingleColumnAtWindowInnerWidth = 700;

settings.EditFormLayoutProperties.Items.AddTabbedGroupItem(tabbedGroupSettings => {
  // ...
})

Learn more | See demo

Data Management

Sort Data

You can sort the grid data by an unlimited number of columns. Use a column's AllowSort property or the grid's AllowSort option to allow end users to sort the specified column or all columns in the grid.

// Control's setting
settings.SettingsBehavior.AllowSort = true;

// Column's setting
settings.Columns.Add(column => {
    column.Settings.AllowSort = DefaultBoolean.False;
});

See demo

Filter Data

You can use the following UI elements to filter grid data:

// Search Panel
settings.SettingsSearchPanel.Visible = true;

// Filter Row
settings.Settings.ShowFilterRow = true;
settings.Settings.ShowFilterRowMenu = true;

// Filter Control
settings.SettingsFilterControl.ViewMode = FilterBuilderOptions.EnableTextTab ? FilterControlViewMode.VisualAndText : FilterControlViewMode.Visual;
settings.SettingsFilterControl.AllowHierarchicalColumns = FilterBuilderOptions.AllowHierarchicalColumns;
settings.SettingsFilterControl.ShowAllDataSourceColumns = FilterBuilderOptions.ShowAllDataSourceColumns;
settings.SettingsFilterControl.MaxHierarchyDepth = 1;

// Header Filter
settings.SettingsPopup.HeaderFilter.Height = Unit.Pixel(440);
settings.SettingsPopup.HeaderFilter.Width = GetHeaderFilterPopupWidth();
settings.SettingsPopup.HeaderFilter.SettingsAdaptivity.Mode = PopupControlAdaptivityMode.OnWindowInnerWidth;
settings.SettingsPopup.HeaderFilter.SettingsAdaptivity.SwitchAtWindowInnerWidth = 768;

Learn more

Group Data

The grid enables you to use drag-and-drop operations (ShowGroupPanel) or APIs to group data against an unlimited number of data columns. Use a column's AllowGroup property or the grid's AllowGroup option to allow end users to group the specified column or all columns in the grid.

// Control's setting
settings.SettingsBehavior.AllowGroup = true;

// Column's setting
settings.Columns.Add(column => {
    column.Settings.AllowGroup = DefaultBoolean.False;
});

See demo

The grid allows you to group grid data by multiple columns at once and combine them into a single grouping level (MergeGroupsMode).

settings.SettingsBehavior.MergeGroupsMode = GridViewMergeGroupsMode.Always;

See demo

Data Summary

The grid allows you to display brief information about groups of rows or individual data columns (summaries) in the footer (ShowFooter). The following summary types are available:

// Total Summary
settings.TotalSummary.Add(DevExpress.Data.SummaryItemType.Count, "CompanyName");

// Group Summary
settings.GroupSummary.Add(DevExpress.Data.SummaryItemType.Sum, "Total").DisplayFormat= "c";

// Custom Summary
settings.CustomSummaryCalculate = (s, e) => {
    ASPxSummaryItem summary = e.Item as ASPxSummaryItem;
    MVCxGridView gridView = s as MVCxGridView;
    if (summary.FieldName != "TotalAmount")
        return;
    if (e.IsGroupSummary) {
        decimal totalValue;
        if (e.SummaryProcess == Start) {
            totalValue = 0;
        } else if (e.SummaryProcess == Calculate) {
            bool isCancelled = (bool)e.GetValue("isCancelled");
            if (!isCancelled) {
                totalValue += (int)e.FieldValue;
            }
        }
        else if (e.SummaryProcess == Finalize) {
            e.TotalValue = totalValue;
            e.TotalValueReady = true;
        }
    }
}

See demo

Master-Detail Grid

The grid supports master-detail data. You can link a master table to multiple detail tables. Each detail table can be the master of another table.

// Master Grid
@Html.DevExpress().GridView(settings => {
    settings.Name = "DetailGrid";
    //...
}).Bind(Model).GetHtml()

// Detail Grid
@Html.DevExpress().GridView(settings => {
    settings.Name = "MasterGrid";
    settings.SettingsDetail.MasterGridName = "DetailGrid";
    //...
}).Bind(Model).GetHtml()

See demo

Validation

The grid supports a model-based data validation when you use jQuery validation and decorate model class properties with the DataAnnotations attributes.

Learn more

Export

The grid allows you to export data in the following formats: PDF, XLS, XLSX, RTF, CSV, DOCX.

settings.SettingsExport.EnableClientSideExportAPI = true;
settings.SettingsExport.ExcelExportMode = DevExpress.Export.ExportType.WYSIWYG;

Learn more | See demo

Merged Cells

The grid can automatically merge adjacent cells with the same values (ASPxGridViewBehaviorSettings.AllowCellMerge, GridViewDataColumnSettings.AllowCellMerge).

settings.SettingsBehavior.AllowCellMerge = true;

See demo

Selection

You can use the UI elements (AllowSelectByRowClick, ShowSelectCheckbox, ShowSelectButton, SelectAllCheckboxMode) or APIs on the client and server side to select grid data.

settings.SettingsBehavior.AllowSelectByRowClick = true;
settings.CommandColumn.ShowSelectCheckbox = true;
settings.CommandColumn.ShowSelectButton = true;
settings.CommandColumn.SelectAllCheckboxMode = GridViewSelectAllCheckBoxMode.AllPages;

Learn more | See demo

Built-In Pager

The grid provides the built-in pager (SettingsPager) that enables end-users to navigate through data. The pager consists of navigation buttons: "next", "last", "previous", "first", "All".

settings.SettingsPager.PageSize = 20;
settings.SettingsPager.FirstPageButton.Visible = true;
settings.SettingsPager.LastPageButton.Visible = true;

Learn more | See demo

Set the Mode property to EndlessPaging to enable endless paging mode that enables you to load grid rows on demand when an end user scrolls the grid.

settings.SettingsPager.Mode = GridViewPagerMode.EndlessPaging;

Learn more | See demo

Scroll Data

Use the HorizontalScrollBarMode and VerticalScrollBarMode properties to enable the horizontal and vertical scroll bars.

settings.Settings.HorizontalScrollBarMode = ScrollBarMode.Visible;
settings.Settings.VerticalScrollBarMode = ScrollBarMode.Visible;

Learn more | See demo

The grid supports virtual paging mode (VerticalScrollBarStyle) that allows end-users to use the vertical scroll bar to navigate through grid pages.

settings.Settings.VerticalScrollBarStyle = GridViewVerticalScrollBarStyle.VirtualSmooth;

Learn more

Keyboard Navigation

The built-in keyboard support allows you to use the keyboard to navigate the grid (KeyboardSupport).

settings.KeyboardSupport = true;

Learn more | See demo

Rows Management

Alternate Row

You can highlight alternating (odd) grid rows with a different style (Enabled).

Preview Row

The preview row displays large memo fields or custom data across all grid columns (ShowPreview, PreviewFieldName).

settings.PreviewFieldName = "Notes";

Learn more | See demo

Grid Lines

The grid allows you to display the horizontal and/or vertical grid lines (GridLines).

settings.Settings.GridLines = GridLines.Horizontal;

Focused Row

You can focus a row in the grid. Note that you can select several records simultaneously but you can focus only one record at a time.

settings.SettingsBehavior.AllowFocusedRow = true;

Learn more | See demo

Customization Tools

Toolbar

The toolbar enables you to group grid commands. The grid stores toolbars (MVCxGridViewToolbar) in its Toolbars collection. You can add or remove toolbars, change their availability and position, and populate them with toolbar items (MVCxGridViewToolbarItem).

settings.Toolbars.Add(tb => {
    tb.Enabled = true;
    tb.Position = GridToolbarPosition.Top;

    tb.Items.Add(GridViewToolbarCommand.New);
    tb.Items.Add(GridViewToolbarCommand.Edit);
    tb.Items.Add(GridViewToolbarCommand.Delete);
    tb.Items.Add(i => {
        i.Command = GridViewToolbarCommand.Refresh;
        i.BeginGroup = true;
        i.AdaptivePriority = 2;
    });
    //...
});

See demo

Customization Dialog

The customization dialog enables users to sort, group, filter, and hide/show columns in the grid on mobile devices.

settings.SettingsCustomizationDialog.Enabled = true;

Learn more | See demo

Context Menu

The grid provides the following context menu types (Enabled):

settings.SettingsContextMenu.Enabled = true;

settings.SettingsContextMenu.RowMenuItemVisibility.ExportMenu.Visible = true;
settings.SettingsContextMenu.RowMenuItemVisibility.GroupSummaryMenu.SummaryAverage = false;
settings.SettingsContextMenu.RowMenuItemVisibility.GroupSummaryMenu.SummaryMax = false;

See demo

Column Chooser

The column chooser allows users to use drag and drop to show/hide columns in the grid (EnableCustomizationWindow)

settings.SettingsBehavior.EnableCustomizationWindow = true;

See demo

Adaptivity

The grid allows you to build adaptive or responsive page layouts. The extension can automatically resize or hide its elements when the browser window is resized (SettingsAdaptivity).

settings.SettingsAdaptivity.AdaptivityMode = GridViewAdaptivityMode.HideDataCellsWindowLimit;
settings.SettingsAdaptivity.HideDataCellsAtWindowInnerWidth = 800;
settings.SettingsAdaptivity.AllowOnlyOneAdaptiveDetailExpanded = true;

Learn more | See demo

Appearance Customization

Templates

The grid supports templates and allows you to customize its UI elements' appearance and layout.

settings.SetDataRowTemplateContent(c => {
    //...
    Html.DevExpress().BinaryImage(imageSettings => {
        imageSettings.Name = "Photo" + DataBinder.Eval(c.DataItem, "EmployeeID");
        imageSettings.Width = 160;
        imageSettings.Height = 170;
    }).Bind(DataBinder.Eval(c.DataItem, "Photo")).Render();
    //...
});

See demo

Conditional Formatting

You can apply format rules (the GridFormatConditionBase object descendants) to the grid (FormatConditions) to customize the appearance of the grid's data.

settings.FormatConditions.AddTopBottom(c => {
    c.FieldName = "Freight";
    c.Rule = GridTopBottomRule.TopPercent;
    c.Threshold = 20;
    c.Format = GridConditionHighlightFormat.RedText;
});

See demo

Miscellaneous

Cookies Support

The grid supports cookies that allow your site's visitors to personalize pages. If cookies are enabled, the browser saves grid options that can be restored in future sessions.

Save and Restore Layout

You can save the grid's layout to a database and then restore it.

Online Demos

Grid View Demos

See Also