SoFunction
Updated on 2025-03-06

Datagridview usage tips (9) Datagridview's right-click menu

DataGridView, DataGridViewColumn, DataGridViewRow, DataGridViewCell has the ContextMenuStrip attribute. 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 of cells other than the line header.

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

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

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

Description: In the parameters of the CellContextMenuStripNeeded event processing method, =-1 represents the column header and =-1 represents the row header. RowContextMenuStripNeeded does not exist =-1.

Example 1:

//Set the right-click menu of DataGridViewthis.dgv_Users.ContextMenuStrip = cmsDgv;
// Set the column's right-click menuthis.dgv_Users.Columns[1].ContextMenuStrip = cmsColumn;
//Set the right-click menu of column headerthis.dgv_Users.Columns[1]. = cmsHeaderCell;
// Set the right-click menu of the linethis.dgv_Users.Rows[2].ContextMenuStrip = cmsRow;
// Set the right-click menu of the cellthis.dgv_Users[1, 2].ContextMenuStrip = cmsCell;

Example 2:

private void dgv_Users_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)
{
 DataGridView dgv = sender as DataGridView;
 if ( < 0)
 {
   //Set the column header right key    = cmsHeaderCell;
 }
 else if ( < 0)
 { 
   //Set the line header menu    = cmsRow;
  }
  else if (dgv[, ].().Equals("male"))
  {
    = cmsCell;
  }
  else
  {
    = cmsDgv;
  }
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.