Example T260978
Visible to All Users

Grid View for ASP.NET Web Forms - How to use the Rich Text Editor to edit formatted text in the Edit Form

This example demonstrates how to add the Rich Text Editor to the Grid View control's edit form. The Rich Text Editor displays formatted text loaded from the data source bound to the Grid View and allows users to edit this text.

Note
Data modification is not allowed in the online version of this example. To allow edit operations, download the example and comment out the throw expression in the RowUpdating event handler.

Overview

Follow the steps below to add the Rich Text Editor in the Grid View's edit form:

  1. Create the Grid View control, populate it with columns, and bind the control to a data source.
  2. Add the Rich Text Editor control to the EditItemTemplate of the column that contains formatted text.
  3. Handle the Rich Text Editor control's Init event that occurs after the edit form appears. Use the Grid View's IsNewRowEditing property to identify if the edit form appeared in response to a click on the New or Edit button. If a user clicked the New button, assign a new unique identifier to the Rich Text Editor's DocumentId property. Otherwise, get a formatted text string from the corresponding cell and pass the string and the row key to the control's Open method.
  4. Handle the Grid View's RowInserting and RowUpdating events. In both event handlers, call the Rich Text Editor control's SaveCopy method to get content of the document opened in the control as an array of bytes. Save the array back to the data source.
  5. To prevent synchronization issues, handle the Rich Text Editor's client-side Init event and the Grid View's client-side BeginCallback event as follows:
    JavaScript
    function OnRichEditInit(s, e) { s.requestSettings.pendingPeriod = 1; } function OnGridBeginCallback(s, e) { if (e.command == "UPDATEEDIT") re.updateWatcherHelper.HasChanges = function () { return false; } }

Files to Review

Documentation

More Examples

Example Code

Default.aspx.cs(vb)
C#
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Text; using DevExpress.Web; using DevExpress.Web.ASPxRichEdit; using DevExpress.Web.Data; using DevExpress.Web.Office; using DevExpress.XtraRichEdit; //for online demos and examples public class CustomCallbackException: Exception { public CustomCallbackException(string message) : base(message) { } } public partial class _Default: System.Web.UI.Page { private string OpenedCanceledDocumentIDsSessionKey = "OpenedCanceledDocumentIDsSessionKey"; private List<string> OpenedCanceledDocumentIDs { get { if (Session[OpenedCanceledDocumentIDsSessionKey] == null) { Session[OpenedCanceledDocumentIDsSessionKey] = new List<string>(); } return (List<string>)Session[OpenedCanceledDocumentIDsSessionKey]; } set { Session[OpenedCanceledDocumentIDsSessionKey] = value; } } protected void re_Init(object sender, EventArgs e) { ASPxRichEdit richEdit = sender as ASPxRichEdit; GridViewEditItemTemplateContainer container = richEdit.NamingContainer as GridViewEditItemTemplateContainer; string documentID = GetDocumentID(container.Grid); if (!OpenedCanceledDocumentIDs.Contains(documentID)) { OpenedCanceledDocumentIDs.Add(documentID); } if (container.Grid.IsNewRowEditing) { richEdit.DocumentId = documentID; return; } //for text in db string rtfText = container.Grid.GetRowValues(container.VisibleIndex, "RtfContent").ToString(); //for binary in db //byte[] rtfBinary = (byte[])container.Grid.GetRowValues(container.VisibleIndex, "RtfContent"); richEdit.Open(documentID, DocumentFormat.Rtf, () => { //for text in db return Encoding.UTF8.GetBytes(rtfText); //for binary in db //return rtfBinary; }); } protected void gv_RowInserting(object sender, ASPxDataInsertingEventArgs e) { ProcessDocument(sender as ASPxGridView, e.NewValues); } protected void gv_RowUpdating(object sender, ASPxDataUpdatingEventArgs e) { ProcessDocument(sender as ASPxGridView, e.NewValues); } protected void gv_AfterPerformCallback(object sender, ASPxGridViewAfterPerformCallbackEventArgs e) { if (e.CallbackName == "ADDNEWROW" || e.CallbackName == "STARTEDIT" || e.CallbackName == "CANCELEDIT") { foreach (string id in OpenedCanceledDocumentIDs) { DocumentManager.CloseDocument(id); } OpenedCanceledDocumentIDs.Clear(); } } protected void gv_CustomErrorText(object sender, ASPxGridViewCustomErrorTextEventArgs e) { if (e.Exception is CustomCallbackException) { e.ErrorText = e.Exception.Message; } } private string GetDocumentID(ASPxGridView grid) { //TODO: For per-user editing, construct the DocumentID using the row's key plus user info, for example, System.Web.UI.User.Identity.Name. Then, close the document for editing by this DocumentID for this user only. if (grid.IsNewRowEditing) return Guid.NewGuid().ToString(); else return grid.GetRowValues(grid.EditingRowVisibleIndex, grid.KeyFieldName).ToString(); } private ASPxRichEdit GetRichEdit(ASPxGridView grid) { GridViewDataColumn columnRftContent = grid.Columns["RtfContent"] as GridViewDataColumn; return grid.FindEditRowCellTemplateControl(columnRftContent, "re") as ASPxRichEdit; } private void ProcessDocument(ASPxGridView grid, OrderedDictionary newValues) { ASPxRichEdit richEdit = GetRichEdit(grid); //for text in db newValues["RtfContent"] = Encoding.UTF8.GetString(richEdit.SaveCopy(DocumentFormat.Rtf)); //for binary in db //newValues["RtfContent"] = richEdit.SaveCopy(DocumentFormat.Rtf); throw new CustomCallbackException("Data modifications are not allowed in online demos"); //Note that data modifications are not allowed in online demos. To allow editing in local/offline mode, download the example and comment out the "throw..." operation in the ASPxGridView.RowUpdating event handler. OpenedCanceledDocumentIDs.Remove(richEdit.DocumentId); DocumentManager.CloseDocument(richEdit.DocumentId); } }
Default.aspx
ASPx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <%@ Register Assembly="DevExpress.Web.ASPxRichEdit.v19.2, Version=19.2.15.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" Namespace="DevExpress.Web.ASPxRichEdit" TagPrefix="dx" %> <%@ Register Assembly="DevExpress.Web.v19.2, Version=19.2.15.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" Namespace="DevExpress.Web" TagPrefix="dx" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script type="text/javascript"> function OnRichEditInit(s, e) { s.requestSettings.pendingPeriod = 1; } function OnGridBeginCallback(s, e) { if (e.command == "UPDATEEDIT") re.updateWatcherHelper.HasChanges = function () { return false; } } </script> </head> <body> <form id="form1" runat="server"> <dx:ASPxGridView ID="gv" runat="server" AutoGenerateColumns="False" DataSourceID="ads" KeyFieldName="ID" OnRowUpdating="gv_RowUpdating" OnCustomErrorText="gv_CustomErrorText" OnRowInserting="gv_RowInserting" OnAfterPerformCallback="gv_AfterPerformCallback"> <ClientSideEvents BeginCallback="OnGridBeginCallback" /> <Columns> <dx:GridViewCommandColumn VisibleIndex="0" ShowNewButton="true" ShowEditButton="True" ShowDeleteButton="true" /> <dx:GridViewDataTextColumn FieldName="ID" ReadOnly="True" VisibleIndex="1"> <EditFormSettings Visible="False" /> </dx:GridViewDataTextColumn> <dx:GridViewDataTextColumn FieldName="Trademark" VisibleIndex="2"> </dx:GridViewDataTextColumn> <dx:GridViewDataTextColumn FieldName="Model" VisibleIndex="3"> </dx:GridViewDataTextColumn> <dx:GridViewDataTextColumn FieldName="RtfContent" VisibleIndex="4" Visible="false"> <EditFormSettings Visible="True" /> <EditItemTemplate> <dx:ASPxRichEdit ID="re" runat="server" OnInit="re_Init" ClientInstanceName="re"> <ClientSideEvents Init="OnRichEditInit" /> </dx:ASPxRichEdit> </EditItemTemplate> </dx:GridViewDataTextColumn> </Columns> <SettingsEditing EditFormColumnCount="1"> </SettingsEditing> </dx:ASPxGridView> <asp:AccessDataSource ID="ads" runat="server" DataFile="~/App_Data/CarsDB.mdb" SelectCommand="SELECT [ID], [Trademark], [Model], [RtfContent] FROM [Cars]" InsertCommand="INSERT INTO [Cars] ([ID], [Trademark], [Model], [RtfContent]) VALUES (?, ?, ?, ?)" UpdateCommand="UPDATE [Cars] SET [Trademark] = ?, [Model] = ?, [RtfContent] = ? WHERE [ID] = ?" DeleteCommand="DELETE FROM [Cars] WHERE [ID] = ?"> <InsertParameters> <asp:Parameter Name="ID" Type="Int32" /> <asp:Parameter Name="Trademark" Type="String" /> <asp:Parameter Name="Model" Type="String" /> <asp:Parameter Name="RtfContent" Type="String" /> </InsertParameters> <UpdateParameters> <asp:Parameter Name="Trademark" Type="String" /> <asp:Parameter Name="Model" Type="String" /> <asp:Parameter Name="RtfContent" Type="String" /> <asp:Parameter Name="ID" Type="Int32" /> </UpdateParameters> <DeleteParameters> <asp:Parameter Name="ID" Type="Int32" /> </DeleteParameters> </asp:AccessDataSource> </form> </body> </html>

Disclaimer: The information provided on DevExpress.com and affiliated web properties (including the DevExpress Support Center) is provided "as is" without warranty of any kind. Developer Express Inc disclaims all warranties, either express or implied, including the warranties of merchantability and fitness for a particular purpose. Please refer to the DevExpress.com Website Terms of Use for more information in this regard.

Confidential Information: Developer Express Inc does not wish to receive, will not act to procure, nor will it solicit, confidential or proprietary materials and information from you through the DevExpress Support Center or its web properties. Any and all materials or information divulged during chats, email communications, online discussions, Support Center tickets, or made available to Developer Express Inc in any manner will be deemed NOT to be confidential by Developer Express Inc. Please refer to the DevExpress.com Website Terms of Use for more information in this regard.