Tips for using Datagridview (9) Right click menu of Datagridview

  • 2021-12-12 09:28:17
  • OfStack

DataGridView, DataGridViewColumn, DataGridViewRow, DataGridViewCell have ContextMenuStrip attributes. You can control the display of the right-click menu of DataGridView by setting the ContextMenuStrip object.

The ContextMenuStrip property of DataGridViewColumn sets the right-click menu for cells other than column headers.

The ContextMenuStrip property of DataGridViewRow sets the right-click menu for cells other than wardrobe.

The ContextMenuStrip property of DataGridViewCell sets the right-click menu for the specified cell.

For the setting of the right-click menu on the cell, the priority order is: Cell > Row > Column > DataGridView

Using CellContextMenuStripNeeded, RowContextMenuStripNeeded events can set the right-click menu of a cell, especially when the right-click menu needs to change according to the change of cell value. It is more efficient to use this event to set the right-click menu than to use loop traversal.

Description: CellContextMenuStripNeeded event processing method parameters, e. RowIndex=-1 for column header, e. ColumnIndex=-1 for line header. RowContextMenuStripNeeded does not have e. ColumnIndex=-1.

Example 1:


// Settings DataGridView Right-click menu of 
this.dgv_Users.ContextMenuStrip = cmsDgv;
// Set the right-click menu of columns 
this.dgv_Users.Columns[1].ContextMenuStrip = cmsColumn;
// Set the right-click menu of column headers 
this.dgv_Users.Columns[1].HeaderCell.ContextMenuStrip = cmsHeaderCell;
// Set the right-click menu of the row 
this.dgv_Users.Rows[2].ContextMenuStrip = cmsRow;
// Set the right-click menu of the cell 
this.dgv_Users[1, 2].ContextMenuStrip = cmsCell;

Example 2:


private void dgv_Users_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)
{
 DataGridView dgv = sender as DataGridView;
 if (e.RowIndex < 0)
 {
   // Set the column header right key 
   e.ContextMenuStrip = cmsHeaderCell;
 }
 else if (e.ColumnIndex < 0)
 { 
   // Set the right-click menu of outfit 
   e.ContextMenuStrip = cmsRow;
  }
  else if (dgv[e.ColumnIndex, e.RowIndex].Value.ToString().Equals(" Male "))
  {
   e.ContextMenuStrip = cmsCell;
  }
  else
  {
   e.ContextMenuStrip = cmsDgv;
  }
}

Related articles: