FlexGrid
Editing
Features
Editing
Excel-Style editing
The FlexGrid has built-in support for Excel-like, fast, in-cell editing. There is no need to add extra columns with 'Edit' buttons that switch between display and edit modes.
Users can start editing simply by typing into any cell. This is called 'quick-edit' mode. In this mode, the cursor keys finish the editing and the grid moves the selection. They can also start editing by pressing F2 or by clicking a cell twice. This is called 'full-edit' mode. In this mode, the cursor keys move the caret within the editor and the user must press the Enter, Tab, or Escape keys to finish editing.
You can disable editing at the grid or column levels using the isReadOnly property of the grid or column objects.
Mobile Devices: Mobile devices use the double-click event to zoom in and out, and do not show a keyboard by default. To start editing a cell on mobile devices, simply click a cell to select it, then click it again to indicate you want to start editing.
Automatic type Validation/Coercion: If the user types anything that is invalid for the column (e.g. "hello" for a numeric or date column), the edits won't be applied and the cell will keep its original value. Dates and times are parsed using the format assigned to the column.
Checkboxes: By default (and unlike Excel), Boolean values are shown as checkboxes. Users can change the checkbox values by clicking or by pressing the space bar. Checkboxes are easier to read and to edit than fields containing "TRUE" or "FALSE" strings.
Multiline: When setting the column's multiline property to true, the content of cells in column would wrap at new line characters (\n). Like Excel, users can press ALT+ENTER to enter a new line.
Editing Mode: There are two modes for updating the data. By default, the update operation will be commit to the server once finishing editing. If the user wants to commit the update operation to datasource server, the Update, Delete or Create action url should be provided. And the corresponding codes used to update the datasource should be written in the corresponding action. The other mode is called BatchEdit. The user can update, create or remove multiple items. Once these modifications are confirmed, They could be commit to the data source only once. Now these modifications can be commit by the commit method of CollectionView in client side. The user can also commit them by sorting, paging or filtering behavior.
AutoRowHeights: Automatically resize the rows when the data or grid layout change. Especially useful when the grid has columns configured to word-wrap their content, and when the grid has a relatively small number of rows.
RefreshOnEdit: This determines whether the grid should refresh all cells after a cell is edited. It's True by default, you can disable this for more perfomance.
ShowPlaceholders: This setting determines whether the grid should use the column headers as placeholders when editing cells. It only works with the grid's built-in editor. It's not useful in IE because IE does not show input placeholders on focused input elements.
Here is a typical editable grid, the Description column shows text in multiline.
Edit Item
- Category ID
- Category Name
- Description
Popup editing
Popup editing keeps the native editing enabled for quick Excel-like data entry, and adds an "Edit Detail" button to invoke a form where the user can edit the item details.
To see this in action, select an item on the grid and click the "Edit Detail" button below. This will bring up a form where users can edit the data for the currently selected item.
The detail form uses specialized input controls that take up more space but can make data entry easier in some cases. The form has "OK" and "Cancel" buttons that commit the changes or restore the original data. Both actions are accomplished with a single call to the CollectionView used as a data source for the grid.
Inline editing
If for some reason you don't like the Excel-style editing and prefer to add editing buttons to every row (typical of editable HTML tables), you can accomplish that using a cellFormatter and a few controller methods.
The grid below demonstrates this approach. The buttons in the cells call methods in the controller to perform the required actions:
using C1.Web.Mvc; using System; using System.Linq; using C1.Web.Mvc.Serialization; using Microsoft.AspNetCore.Mvc; using MvcExplorer.Models; using System.Data.SqlClient; using Microsoft.EntityFrameworkCore; namespace MvcExplorer.Controllers { public partial class FlexGridController : Controller { private readonly C1NWindEntities _db; public FlexGridController(C1NWindEntities db) { _db = db; } public ActionResult Editing() { return View(); } public ActionResult GridBindCategory([C1JsonRequest] CollectionViewRequest<Category> requestData) { return this.C1Json(CollectionViewHelper.Read(requestData, _db.Categories.ToList())); } public ActionResult GridUpdateCategory([C1JsonRequest]CollectionViewEditRequest<Category> requestData) { return Update(requestData, _db.Categories); } public ActionResult GridCreateCategory([C1JsonRequest]CollectionViewEditRequest<Category> requestData) { var category = requestData.OperatingItems.First(); if (category.CategoryName == null) { category.CategoryName = ""; } return Create(requestData, _db.Categories); } public ActionResult GridDeleteCategory([C1JsonRequest]CollectionViewEditRequest<Category> requestData) { return Delete(requestData, _db.Categories, item => item.CategoryID); } public ActionResult GridBindCustomer([C1JsonRequest] CollectionViewRequest<Customer> requestData) { return this.C1Json(CollectionViewHelper.Read(requestData, _db.Customers.ToList())); } public ActionResult GridUpdateCustomer([C1JsonRequest]CollectionViewEditRequest<Customer> requestData) { return Update(requestData, _db.Customers); } public ActionResult GridCreateCustomer([C1JsonRequest]CollectionViewEditRequest<Customer> requestData) { return Create(requestData, _db.Customers); } public ActionResult GridDeleteCustomer([C1JsonRequest]CollectionViewEditRequest<Customer> requestData) { return Delete(requestData, _db.Customers, item => item.CustomerID); } private ActionResult Update<T>(CollectionViewEditRequest<T> requestData, DbSet<T> data) where T : class { return this.C1Json(CollectionViewHelper.Edit<T>(requestData, item => { string error = string.Empty; bool success = true; try { _db.Entry(item as object).State = EntityState.Modified; _db.SaveChanges(); } catch (Exception e) { error = GetExceptionMessage(e); success = false; } return new CollectionViewItemResult<T> { Error = error, Success = success, Data = item }; }, () => data.ToList<T>())); } private ActionResult Create<T>(CollectionViewEditRequest<T> requestData, DbSet<T> data) where T : class { return this.C1Json(CollectionViewHelper.Edit<T>(requestData, item => { string error = string.Empty; bool success = true; try { data.Add(item); _db.SaveChanges(); } catch (Exception e) { error = GetExceptionMessage(e); success = false; } return new CollectionViewItemResult<T> { Error = error, Success = success, Data = item }; }, () => data.ToList<T>())); } private ActionResult Delete<T>(CollectionViewEditRequest<T> requestData, DbSet<T> data, Func<T, object> getKey) where T : class { return this.C1Json(CollectionViewHelper.Edit(requestData, item => { string error = string.Empty; bool success = true; try { T resultItem = null; foreach (var i in data) { if(string.Equals(getKey(i).ToString(), getKey(item).ToString())) { resultItem = i; break; } } if (resultItem != null) { data.Remove(resultItem); _db.SaveChanges(); } } catch (Exception e) { error = GetExceptionMessage(e); success = false; } return new CollectionViewItemResult<T> { Error = error, Success = success, Data = item }; }, () => data.ToList())); } /// <summary> /// In order to get the real exception message. /// </summary> private static SqlException GetSqlException(Exception e) { while(e != null && !(e is SqlException)) { e = e.InnerException; } return e as SqlException; } // Get the real exception message internal static string GetExceptionMessage(Exception e) { var msg = e.Message; var sqlException = GetSqlException(e); if (sqlException != null) { msg = sqlException.Message; } return msg; } } }
@model C1NWindEntities @{ ViewBag.DemoDescription = false; } @section Summary{ @Html.Raw(FlexGridRes.Editing_Text15) } <h3> @Html.Raw(FlexGridRes.Editing_Editing) </h3> <h4> @Html.Raw(FlexGridRes.Editing_ExcelStyleEditing) </h4> <p>@Html.Raw(FlexGridRes.Editing_Text0)</p> <p>@Html.Raw(FlexGridRes.Editing_Text1)</p> <div class="collapsed-content collapse"> <p>@Html.Raw(FlexGridRes.Editing_Text2)</p> <p>@Html.Raw(FlexGridRes.Editing_Text3)</p> <p>@Html.Raw(FlexGridRes.Editing_Text4)</p> <p>@Html.Raw(FlexGridRes.Editing_Text5)</p> <p>@Html.Raw(FlexGridRes.Editing_Text6)</p> <p>@Html.Raw(FlexGridRes.Editing_Text7)</p> <p>@Html.Raw(FlexGridRes.Editing_Text8)</p> <p>@Html.Raw(FlexGridRes.Editing_Text16)</p> <p>@Html.Raw(FlexGridRes.Editing_Text17)</p> </div> <input type="button" value="@FlexGridRes.Editing_ReadMore" class="btn collapse in" data-toggle="collapse" data-target=".collapsed-content, .btn.collapse" /> <p>@Html.Raw(FlexGridRes.Editing_Text9)</p> <c1-flex-grid id="editGrid" auto-generate-columns="false" allow-add-new="true" auto-row-heights="true" allow-delete="true" refresh-on-edit="false" show-placeholders="true" style="height:400px"> <c1-flex-grid-column binding="CategoryID" is-read-only="true" format="d"></c1-flex-grid-column> <c1-flex-grid-column binding="CategoryName" word-wrap="true"></c1-flex-grid-column> <c1-flex-grid-column binding="Description" word-wrap="true" width="*" multi-line="true"></c1-flex-grid-column> <c1-items-source read-action-url="@Url.Action("GridBindCategory")" update-action-url="@Url.Action("GridUpdateCategory")" create-action-url="@Url.Action("GridCreateCategory")" delete-action-url="@Url.Action("GridDeleteCategory")"></c1-items-source> </c1-flex-grid> <!-- a dialog for editing item details --> <div class="modal fade" id="dlgDetail"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> × </button> <h4 class="modal-title">@Html.Raw(FlexGridRes.Editing_DialogTitle)</h4> </div> <div class="modal-body"> <dl class="dl-horizontal"> <dt>@Html.Raw(FlexGridRes.Editing_CategoryID)</dt> <dd> <input id="CategoryID" class="form-control" disabled /> </dd> <dt>@Html.Raw(FlexGridRes.Editing_CategoryName)</dt> <dd> <input id="CategoryName" class="form-control" /> </dd> <dt>@Html.Raw(FlexGridRes.Editing_Description)</dt> <dd> <textarea id="Description" class="form-control"></textarea> </dd> </dl> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" data-dismiss="modal" onclick="commitUpdate()"> <span class="glyphicon glyphicon-ok"></span> @Html.Raw(FlexGridRes.Editing_OK) </button> <button type="button" class="btn btn-warning" data-dismiss="modal"> <span class="glyphicon glyphicon-ban-circle"></span> @Html.Raw(FlexGridRes.Editing_Cancel) </button> </div> </div><!-- modal-content --> </div><!-- modal-dialog --> </div><!-- modal --> <div class="well grid-sort-group"> <!-- edit details in a popup --> <button id="showEditDialogBtn" class="btn btn-default" data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#dlgDetail" onclick="showEditDialog()"> <span class="glyphicon glyphicon-new-window"></span> @Html.Raw(FlexGridRes.Editing_EditDetail) </button> </div> <h4> @Html.Raw(FlexGridRes.Editing_PopupEditing) </h4> <p>@Html.Raw(FlexGridRes.Editing_Text10)</p> <p>@Html.Raw(FlexGridRes.Editing_Text11)</p> <p>@Html.Raw(FlexGridRes.Editing_Text12)</p> <br /> <h4> @Html.Raw(FlexGridRes.Editing_InlineEditing) </h4> <p>@Html.Raw(FlexGridRes.Editing_Text13)</p> <p>@Html.Raw(FlexGridRes.Editing_Text14)</p> <c1-flex-grid id="inlineEditGrid" is-read-only="true" selection-mode="None" pinning-type="SingleColumn" pinned-column="pinnedColumn" auto-generate-columns="false" item-formatter="itemFormatter" style="height:400px" refresh-on-edit="false" scroll-position-changed="scrollPositionChanged" resizing-column="resizingColumn" dragging-column="draggingColumn" sorting-column="sortingColumn" pinning-column="pinningColumn"> <c1-items-source read-action-url="@Url.Action("GridBindCustomer")" update-action-url="@Url.Action("GridUpdateCustomer")" create-action-url="@Url.Action("GridCreateCustomer")" delete-action-url="@Url.Action("GridDeleteCustomer")"></c1-items-source> <c1-flex-grid-column binding="CustomerID" width="80" align="right" is-read-only="true"></c1-flex-grid-column> <c1-flex-grid-column binding="Country" name="Country"></c1-flex-grid-column> <c1-flex-grid-column binding="Address" width="*" name="Address"></c1-flex-grid-column> <c1-flex-grid-column name="Buttons" width="170"></c1-flex-grid-column> </c1-flex-grid> @section Scripts{ <script type="text/javascript" src="~/Scripts/jquery.js"></script> <script type="text/javascript" src="~/Scripts/BootStrap/bootstrap.js"></script> <script> var editGrid, editCV, minHeight, showEditDialogBtn, idInput, categoryNameInput, descriptionInput; c1.documentReady(function () { editGrid = wijmo.Control.getControl('#editGrid'); editCV = editGrid.collectionView; showEditDialogBtn = document.getElementById('showEditDialogBtn'); idInput = document.getElementById('CategoryID'); categoryNameInput = document.getElementById('CategoryName'); descriptionInput = document.getElementById('Description'); updateButton(); editCV.currentChanged.addHandler(updateButton); minHeight = editGrid.rows.defaultSize; autoSizeEditGridRows(); editCV.collectionChanged.addHandler(autoSizeEditGridRows); }); function autoSizeEditGridRows(s, e) { if (e && e.action == 0) return; editGrid.autoSizeRows(); for (var i = 0, len = editGrid.rows.length; i < len; i++) { var row = editGrid.rows[i]; var height = row.height == undefined ? 0 : row.height; row.height = Math.max(28, height); } } function showEditDialog() { var current; if (!editCV || !editCV.currentItem) { return; } current = editCV.currentItem; // fill the current item data to the inputs. idInput.value = current.CategoryID || ''; categoryNameInput.value = current.CategoryName || ''; descriptionInput.value = current.Description || ''; } function updateButton() { if (!showEditDialogBtn) { return; } if (!editCV || !editCV.currentItem) { showEditDialogBtn.disabled = true; } else { showEditDialogBtn.disabled = false; } } function commitUpdate() { if (!editCV) { return; } var editItem = editCV.currentItem; // begin to edit the current item editCV.editItem(editItem); //update the data editItem.CategoryName = categoryNameInput.value; editItem.Description = descriptionInput.value; // commit the edit editCV.commitEdit(); } var inlineEditGrid, inlineEditCV, editIndex = -1; c1.documentReady(function () { inlineEditGrid = wijmo.Control.getControl('#inlineEditGrid'); inlineEditGrid.rows.defaultSize = 44; inlineEditCV = inlineEditGrid.collectionView; }); function itemFormatter(panel, r, c, cell) { var isLocalHost = (location.hostname === "localhost" || location.hostname === "127.0.0.1"); var col, html, hasUpdated = false; if (panel.cellType == wijmo.grid.CellType.Cell) { col = panel.columns[c]; if (r == editIndex) { switch (col.name) { case 'Country': html = '<input id="theCountry" class="form-control" onkeydown="keyDown(event)" value="' + panel.getCellData(r, c, true) + '"/>'; hasUpdated = true; break; case 'Address': html = '<input id="theAddress" class="form-control" onkeydown="keyDown(event)" value="' + panel.getCellData(r, c, true) + '"/>'; hasUpdated = true; break; case 'Buttons': html = '<div>' + ' ' + '<button class="btn btn-primary btn-sm" onclick="commitRow(' + r + ')">' + '<span class="glyphicon glyphicon-ok"></span> @Html.Raw(FlexGridRes.Editing_OK)' + '</button>' + ' ' + '<button class="btn btn-warning btn-sm" onclick="cancelRow(' + r + ')">' + '<span class="glyphicon glyphicon-ban-circle"></span> @Html.Raw(FlexGridRes.Editing_Cancel)' + '</button>' + '</div>'; hasUpdated = true; break; } } else { switch (col.name) { case 'Buttons': hasUpdated = true; html = '<div>' + ' ' + '<button class="btn btn-default btn-sm" onclick="editRow(' + r + ')">' + '<span class="glyphicon glyphicon-pencil"></span> @Html.Raw(FlexGridRes.Editing_Edit)' + '</button>' + ' ' + '<button class="btn btn-default btn-sm" ' + (isLocalHost ? '' : 'style="display:none"') + ' onclick="deleteRow(' + r + ')">' + '<span class="glyphicon glyphicon-remove"></span> @Html.Raw(FlexGridRes.Editing_Delete)' + '</button>' + '</div>'; break; } } if (hasUpdated) { cell.innerHTML = html; cell.style.padding = '3px'; } } } function scrollPositionChanged() { cancelEditingMode(); } function resizingColumn() { cancelEditingMode(); } function draggingColumn() { cancelEditingMode(); } function sortingColumn() { cancelEditingMode(); } function pinningColumn() { cancelEditingMode(); console.log("Column is pinning."); } function pinnedColumn() { console.log("Column has pinned."); } function cancelEditingMode() { if (editIndex > -1) { cancelRow(editIndex); } } function keyDown(e) { e.stopPropagation(); } function editRow(rowIndex) { if (!inlineEditGrid || !inlineEditCV) { return; } editIndex = rowIndex; inlineEditGrid.invalidate(); } function deleteRow(rowIndex) { if (!inlineEditCV) { return; } editIndex = -1; inlineEditCV.removeAt(rowIndex); } function commitRow(rowIndex) { var countryInput, addressInput, editItem; if (!inlineEditCV) { return; } //update the data inlineEditCV.editItem(inlineEditCV.items[rowIndex]); editItem = inlineEditCV.currentEditItem; if (!editItem) { return; } countryInput = document.getElementById('theCountry'); addressInput = document.getElementById('theAddress'); editItem.Country = countryInput.value; editItem.Address = addressInput.value; editIndex = -1; inlineEditCV.commitEdit(); } function cancelRow() { editIndex = -1; inlineEditGrid.invalidate(); } </script> }