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 MvcExplorer.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using C1.Web.Mvc.Serialization; using System.Data; using System.Collections; using System.Globalization; using System.Data.Entity; using System.Data.Entity.Validation; namespace MvcExplorer.Controllers { public partial class FlexGridController : Controller { private C1NWindEntities db = new C1NWindEntities(); // // GET: /Editing/ public ActionResult Editing() { return View(db); } 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 GridUpdate([C1JsonRequest]CollectionViewEditRequest<Customer> requestData) { return Update(requestData, db.Customers); } public ActionResult GridCreate([C1JsonRequest]CollectionViewEditRequest<Customer> requestData) { return Create(requestData, db.Customers); } public ActionResult GridDelete([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 (DbEntityValidationException e) { error = string.Join(",", e.EntityValidationErrors.Select(result => { return string.Join(",", result.ValidationErrors.Select(err => err.ErrorMessage)); })); success = false; } catch (Exception e) { error = e.Message; success = false; } return new CollectionViewItemResult<T> { Error = error, Success = success && ModelState.IsValid, 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 (DbEntityValidationException e) { error = string.Join(",", e.EntityValidationErrors.Select(result => { return string.Join(",", result.ValidationErrors.Select(err => err.ErrorMessage)); })); success = false; } catch (Exception e) { error = e.Message; success = false; } return new CollectionViewItemResult<T> { Error = error, Success = success && ModelState.IsValid, 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<T>(requestData, item => { string error = string.Empty; bool success = true; try { var resultItem = data.Find(getKey(item)); data.Remove(resultItem); db.SaveChanges(); } catch (DbEntityValidationException e) { error = string.Join(",", e.EntityValidationErrors.Select(result => { return string.Join(",", result.ValidationErrors.Select(err => err.ErrorMessage)); })); success = false; } catch (Exception e) { error = e.Message; success = false; } return new CollectionViewItemResult<T> { Error = error, Success = success && ModelState.IsValid, Data = item }; }, () => data.ToList<T>())); } } }
@model C1NWindEntities @{ ViewBag.DemoDescription = false; } @section Scripts{ @Scripts.Render("~/jquery") @Scripts.Render("~/BootStrapJS") <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> @(Resources.FlexGrid.Editing_OK)' + '</button>' + ' ' + '<button class="btn btn-warning btn-sm" onclick="cancelRow(' + r + ')">' + '<span class="glyphicon glyphicon-ban-circle"></span> @(Resources.FlexGrid.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> @(Resources.FlexGrid.Editing_Edit)' + '</button>' + ' ' + '<button class="btn btn-default btn-sm" ' + (isLocalHost ? '' : 'style="display:none"') + ' onclick="deleteRow(' + r + ')">' + '<span class="glyphicon glyphicon-remove"></span> @(Resources.FlexGrid.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> } @section Summary{ @Html.Raw(Resources.FlexGrid.Editing_Text15) } <h3> @Html.Raw(Resources.FlexGrid.Editing_Editing) </h3> <h4> @Html.Raw(Resources.FlexGrid.Editing_ExcelStyleEditing) </h4> <p>@Html.Raw(Resources.FlexGrid.Editing_Text0)</p> <p>@Html.Raw(Resources.FlexGrid.Editing_Text1)</p> <div class="collapsed-content collapse"> <p>@Html.Raw(Resources.FlexGrid.Editing_Text2)</p> <p>@Html.Raw(Resources.FlexGrid.Editing_Text3)</p> <p>@Html.Raw(Resources.FlexGrid.Editing_Text4)</p> <p>@Html.Raw(Resources.FlexGrid.Editing_Text5)</p> <p>@Html.Raw(Resources.FlexGrid.Editing_Text6)</p> <p>@Html.Raw(Resources.FlexGrid.Editing_Text7)</p> <p>@Html.Raw(Resources.FlexGrid.Editing_Text8)</p> <p>@Html.Raw(Resources.FlexGrid.Editing_Text16)</p> <p>@Html.Raw(Resources.FlexGrid.Editing_Text17)</p> </div> <p> <input type="button" value="@(Resources.FlexGrid.Editing_ReadMore)" class="btn collapse in" data-toggle="collapse" data-target=".collapsed-content, .btn.collapse" /> </p> <p>@Html.Raw(Resources.FlexGrid.Editing_Text9)</p> @(Html.C1().FlexGrid<Category>() .Id("editGrid").AutoGenerateColumns(false) .Columns(columns => { columns.Add(c => c.Binding("CategoryID").IsReadOnly(true).Format("d")); columns.Add(c => c.Binding("CategoryName").WordWrap(true)); columns.Add(c => c.Binding("Description").WordWrap(true).Width("*").MultiLine(true)); }) .Bind( ib => ib.Bind(Model.Categories) .Update(Url.Action("GridUpdateCategory")) .Create(Url.Action("GridCreateCategory")) .Delete(Url.Action("GridDeleteCategory")) ) .AllowAddNew(true) .AllowDelete(true) .AutoRowHeights(true) .RefreshOnEdit(false) .ShowPlaceholders(true) .CssStyle("height", "400px") ) <!-- 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(Resources.FlexGrid.Editing_EditItem)</h4> </div> <div class="modal-body"> <dl class="dl-horizontal"> <dt>@Html.Raw(Resources.FlexGrid.Editing_CategoryID)</dt> <dd> <input id="CategoryID" class="form-control" disabled /> </dd> <dt>@Html.Raw(Resources.FlexGrid.Editing_CategoryName)</dt> <dd> <input id="CategoryName" class="form-control" /> </dd> <dt>@Html.Raw(Resources.FlexGrid.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(Resources.FlexGrid.Editing_OK) </button> <button type="button" class="btn btn-warning" data-dismiss="modal"> <span class="glyphicon glyphicon-ban-circle"></span> @Html.Raw(Resources.FlexGrid.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(Resources.FlexGrid.Editing_EditDetail) </button> </div> <h4> @Html.Raw(Resources.FlexGrid.Editing_PopupEditing) </h4> <p>@Html.Raw(Resources.FlexGrid.Editing_Text10)</p> <p>@Html.Raw(Resources.FlexGrid.Editing_Text11)</p> <p>@Html.Raw(Resources.FlexGrid.Editing_Text12)</p> <br /> <h4> @Html.Raw(Resources.FlexGrid.Editing_InlineEditing) </h4> <p>@Html.Raw(Resources.FlexGrid.Editing_Text13)</p> <p>@Html.Raw(Resources.FlexGrid.Editing_Text14)</p> @(Html.C1().FlexGrid<Customer>() .Id("inlineEditGrid") .IsReadOnly(true) .SelectionMode(C1.Web.Mvc.Grid.SelectionMode.None) .PinningType(C1.Web.Mvc.Grid.PinningType.SingleColumn) .Bind( ib => ib.Bind(Model.Customers) .Update(Url.Action("GridUpdate")) .Create(Url.Action("GridCreate")) .Delete(Url.Action("GridDelete")) ) .AutoGenerateColumns(false) .Columns(clsb => { clsb.Add(cb => cb.Binding("CustomerID").Width("80").Align("right").IsReadOnly(true)); clsb.Add(cb => cb.Binding("Country").Name("Country")); clsb.Add(cb => cb.Binding("Address").Width("*").Name("Address")); clsb.Add().Name("Buttons").Width("170"); }) .ItemFormatter("itemFormatter") .OnClientPinnedColumn("pinnedColumn") .OnClientScrollPositionChanged("scrollPositionChanged") .OnClientResizingColumn("resizingColumn") .OnClientDraggingColumn("draggingColumn") .OnClientSortingColumn("sortingColumn") .OnClientPinningColumn("pinningColumn") .CssStyle("height", "400px") .RefreshOnEdit(false) )