DataGridViewRow.ContextMenuStrip 属性

定义

获取或设置行的快捷菜单。

public override System.Windows.Forms.ContextMenuStrip ContextMenuStrip { get; set; }
public override System.Windows.Forms.ContextMenuStrip? ContextMenuStrip { get; set; }

属性值

与当前 ContextMenuStrip 关联的 DataGridViewRow。 默认值为 null

例外

在获取此属性的值时,行位于 DataGridView 控件中,并且是共享行。

示例

下面的代码示例演示如何使用 DataGridViewColumn.ContextMenuStrip 属性,该属性几乎与 类的 DataGridViewRow 属性相同ContextMenuStrip。 此代码示例是 类中提供的更大代码示例的 DataGridViewColumn 一部分。

ToolStripMenuItem toolStripItem1 = new ToolStripMenuItem();

private void AddContextMenu()
{
    toolStripItem1.Text = "Redden";
    toolStripItem1.Click += new EventHandler(toolStripItem1_Click);
    ContextMenuStrip strip = new ContextMenuStrip();
    foreach (DataGridViewColumn column in dataGridView.Columns)
    {

        column.ContextMenuStrip = strip;
        column.ContextMenuStrip.Items.Add(toolStripItem1);
    }
}

private DataGridViewCellEventArgs mouseLocation;

// Change the cell's color.
private void toolStripItem1_Click(object sender, EventArgs args)
{
    dataGridView.Rows[mouseLocation.RowIndex]
        .Cells[mouseLocation.ColumnIndex].Style.BackColor
        = Color.Red;
}

// Deal with hovering over a cell.
private void dataGridView_CellMouseEnter(object sender,
    DataGridViewCellEventArgs location)
{
    mouseLocation = location;
}

注解

此属性指示在用户右键单击行时显示的快捷菜单,除非 DataGridView 控件 CellContextMenuStripNeeded 事件或行 ContextMenuStrip 属性替代所单击的特定单元格的快捷菜单。

DataGridView当设置控件DataSource属性或其 VirtualMode 属性为 true时,获取 属性的值ContextMenuStripRowContextMenuStripNeeded引发控件的 事件,并返回事件处理程序中指定的 属性的值DataGridViewRowContextMenuStripNeededEventArgs.ContextMenuStrip。 如果事件没有处理程序,则获取 属性的值 ContextMenuStrip 将返回先前指定的值或其默认值 null

RowContextMenuStripNeeded处理大量数据时,处理事件主要有用,以避免在设置多行的行ContextMenuStrip值时造成性能损失。 有关详细信息,请参阅 缩放 Windows 窗体 DataGridView 控件的最佳做法

更改此属性将在 RowContextMenuStripChanged 拥有 DataGridView的 上引发 事件(如果存在)。

如果当前行是共享的,请使用 GetContextMenuStrip 方法,而不是获取此属性的值。

适用于

产品 版本
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10

另请参阅