How to: Implement Custom Menu in XtraGrid Control
- 3 minutes to read
The following example shows how to use the GridView.PopupMenuShowing event to create a custom menu in the Data Grid control. The created menu is displayed when you right-click within a data row or group row. It contains a ‘Rows’ submenu with a single “Delete this row” regular button, and a ‘Cell Merging’ check button.
A click on the ‘Delete this row’ button invokes the ColumnView.DeleteRow method. The ‘Cell Merging’ check button toggles the GridOptionsView.AllowCellMerge option.
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.Utils.Menu;
using DevExpress.XtraEditors;
private void gridView1_PopupMenuShowing(object sender, PopupMenuShowingEventArgs e) {
GridView view = sender as GridView;
if (e.MenuType == DevExpress.XtraGrid.Views.Grid.GridMenuType.Row) {
int rowHandle = e.HitInfo.RowHandle;
// Delete existing menu items, if any.
e.Menu.Items.Clear();
// Add the Rows submenu with the 'Delete Row' command
e.Menu.Items.Add(CreateSubMenuRows(view, rowHandle));
// Add the 'Cell Merging' check menu item.
DXMenuItem item = CreateMenuItemCellMerging(view, rowHandle);
item.BeginGroup = true;
e.Menu.Items.Add(item);
}
}
DXMenuItem CreateSubMenuRows(GridView view, int rowHandle) {
DXSubMenuItem subMenu = new DXSubMenuItem("Rows");
string deleteRowsCommandCaption;
if (view.IsGroupRow(rowHandle))
deleteRowsCommandCaption = "&Delete rows in this group";
else
deleteRowsCommandCaption = "&Delete this row";
DXMenuItem menuItemDeleteRow = new DXMenuItem(deleteRowsCommandCaption, new EventHandler(OnDeleteRowClick), imageCollection1.Images[0]);
menuItemDeleteRow.Tag = new RowInfo(view, rowHandle);
menuItemDeleteRow.Enabled = view.IsDataRow(rowHandle) || view.IsGroupRow(rowHandle);
subMenu.Items.Add(menuItemDeleteRow);
return subMenu;
}
DXMenuCheckItem CreateMenuItemCellMerging(GridView view, int rowHandle) {
DXMenuCheckItem checkItem = new DXMenuCheckItem("Cell &Merging",
view.OptionsView.AllowCellMerge, null, new EventHandler(OnCellMergingClick));
checkItem.Tag = new RowInfo(view, rowHandle);
checkItem.ImageOptions.Image = imageCollection1.Images[1];
return checkItem;
}
void OnDeleteRowClick(object sender, EventArgs e) {
DXMenuItem menuItem = sender as DXMenuItem;
RowInfo ri = menuItem.Tag as RowInfo;
if (ri != null) {
string message = menuItem.Caption.Replace("&", "");
if (XtraMessageBox.Show(message + " ?", "Confirm operation", MessageBoxButtons.YesNo) != DialogResult.Yes)
return;
ri.View.DeleteRow(ri.RowHandle);
}
}
void OnCellMergingClick(object sender, EventArgs e) {
DXMenuCheckItem item = sender as DXMenuCheckItem;
RowInfo info = item.Tag as RowInfo;
info.View.OptionsView.AllowCellMerge = item.Checked;
}
class RowInfo {
public RowInfo(GridView view, int rowHandle) {
this.RowHandle = rowHandle;
this.View = view;
}
public GridView View;
public int RowHandle;
}