In this tutorial, we will look at how to replace the default ContextMenu of the XtraGrid’s inplace editor with our own.

1.  Here, I have simple form with an XtraGrid control bound to a customers table.

2.  To assign a custom ContextMenu I will respond the XtraGrid’s ShownEditor event. This event is fired whenever an inplace editor is about to be displayed. And we can write custom code to further customize the behavior of that inplace editor.

3.  I will select the gridView1 and find the ShownEditor event in the properties window.

4.  I will call my event handler OnEditorShown.

5.  The GridView exposes the ActiveEditor property for the currently selected inplace editor. We will assign a custom menu to the ActiveEditor.ContextMenu. This will tell the grid control to use our menu, instead of the default one.

private void OnEditorShown(object sender, EventArgs e) {

if (inplaceContextMenu == null) {

InitializeCustomContextMenu();

}

this.gridView1.ActiveEditor.ContextMenu = cm;

}

6.  Let’s take a look “InitializeCustomContextMenu” routine.

private void InitializeCustomContextMenu() {

cm = new ContextMenu();

cm.MenuItems.Add(new MenuItem("Cut", new EventHandler(OnCut)));

cm.MenuItems.Add(new MenuItem("Copy", new EventHandler(OnCopy)));

cm.MenuItems.Add(new MenuItem("Paste", new EventHandler(OnPaste)));

cm.MenuItems.Add("-");

cm.MenuItems.Add(new MenuItem("Select All", new EventHandler(OnSelectAll)));

}

7.  Here, we simply create a new ContextMenu and add the desired items. For example, we’ll add Cut, Copy, Paste and Select All with the appropriate click handlers for each one.

8.  So in the OnCut, we’ll invoke the inplace editor’s Cut() method.

private void OnCut(object sender, EventArgs e) {

TextEdit textEdit = this.gridView1.ActiveEditor as TextEdit;

if (textEdit != null) {

textEdit.Cut();

}

}

9.  In the OnCopy, the Copy() method and so on.

private void OnCopy(object sender, EventArgs e) {

TextEdit textEdit = this.gridView1.ActiveEditor as TextEdit;

if (textEdit != null) {

textEdit.Copy();

}

}

10.  I run the application to see the results.

11.  I right-click on any of the cells and the custom context menu is displayed.


Thanks for watching and thank you for choosing DevExpress.