SoFunction
Updated on 2025-03-07

DataGridView clears displayed data and sets the right-click menu

1. Clear the data

1. Clear data when DataGridView is not bound to

this.dgv_PropDemo.DataSource = null

2. Clear data when DataGridView binds data

If the DataGridView is bound to data, you cannot use this.dgv_PropDemo.DataSource = null to clear the data. Using this.dgv_PropDemo.DataSource = null will not only clear the data, but also clear the columns of the DataGridView. At this time, you must use the following code to clear the displayed data:

DataTable dt = this.dgv_PropDemo.DataSource as DataTable;
();
this.dgv_PropDemo.DataSource = dt;

2. Set the 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;
     }
}

This is the end of this article about DataGridView clearing the displayed data and setting the right-click menu. I hope it will be helpful to everyone's learning and I hope everyone will support me more.