DataGridViewRow.ContextMenuStrip Свойство

Определение

Возвращает или задает контекстное меню для строки.

public:
 virtual property System::Windows::Forms::ContextMenuStrip ^ ContextMenuStrip { System::Windows::Forms::ContextMenuStrip ^ get(); void set(System::Windows::Forms::ContextMenuStrip ^ value); };
public override System.Windows.Forms.ContextMenuStrip ContextMenuStrip { get; set; }
public override System.Windows.Forms.ContextMenuStrip? ContextMenuStrip { get; set; }
member this.ContextMenuStrip : System.Windows.Forms.ContextMenuStrip with get, set
Public Overrides Property ContextMenuStrip As ContextMenuStrip

Значение свойства

Объект ContextMenuStrip, сопоставленный с текущим столбцом DataGridViewRow. Значение по умолчанию — null.

Исключения

При получении значения этого свойства, строка должна находиться в элементе управления DataGridView и быть совместно используемой строкой.

Примеры

В следующем примере кода показано, как использовать DataGridViewColumn.ContextMenuStrip свойство , которое почти идентично свойству ContextMenuStripDataGridViewRow класса . Этот пример кода является частью более крупного примера кода, предоставленного DataGridViewColumn в классе .

ToolStripMenuItem^ toolStripItem1;
void AddContextMenu()
{
   toolStripItem1->Text = L"Redden";
   toolStripItem1->Click += gcnew EventHandler( this, &DataGridViewColumnDemo::toolStripItem1_Click );
   System::Windows::Forms::ContextMenuStrip^ strip = gcnew System::Windows::Forms::ContextMenuStrip;
   IEnumerator^ myEnum = dataGridView->Columns->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      DataGridViewColumn^ column = safe_cast<DataGridViewColumn^>(myEnum->Current);
      column->ContextMenuStrip = strip;
      column->ContextMenuStrip->Items->Add( toolStripItem1 );
   }
}

DataGridViewCellEventArgs^ mouseLocation;

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


// Deal with hovering over a cell.
void dataGridView_CellMouseEnter( Object^ /*sender*/, DataGridViewCellEventArgs^ location )
{
   mouseLocation = location;
}
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;
}
WithEvents toolStripItem1 As New ToolStripMenuItem()

Private Sub AddContextMenu()
    toolStripItem1.Text = "Redden"
    Dim strip As New ContextMenuStrip()
    For Each column As DataGridViewColumn _
        In dataGridView.Columns()

        column.ContextMenuStrip = strip
        column.ContextMenuStrip.Items.Add(toolStripItem1)
    Next
End Sub
' Change the cell's color.
Private Sub toolStripItem1_Click(ByVal sender As Object, _
    ByVal args As EventArgs) _
    Handles toolStripItem1.Click

    dataGridView.Rows(mouseLocation.RowIndex) _
        .Cells(mouseLocation.ColumnIndex) _
        .Style.BackColor = Color.Red
End Sub

Private mouseLocation As DataGridViewCellEventArgs

' Deal with hovering over a cell.
Private Sub dataGridView_CellMouseEnter(ByVal sender As Object, _
    ByVal location As DataGridViewCellEventArgs) _
    Handles DataGridView.CellMouseEnter

    mouseLocation = location
End Sub

Комментарии

Это свойство указывает контекстное меню, которое отображается, когда пользователь щелкает строку правой кнопкой мыши, если DataGridView только событие элемента управления CellContextMenuStripNeeded или свойство row ContextMenuStrip не переопределяют контекстное меню для конкретной ячейки, на которую была выполнена щелчок.

DataGridView Если свойство элемента управления DataSource задано или его VirtualMode свойство равно true, получение значения ContextMenuStrip свойства вызывает RowContextMenuStripNeeded событие элемента управления и возвращает значение свойства, указанное DataGridViewRowContextMenuStripNeededEventArgs.ContextMenuStrip в обработчике событий. Если обработчики для события отсутствуют, получение значения ContextMenuStrip свойства возвращает ранее указанное значение или значение nullпо умолчанию .

RowContextMenuStripNeeded Обработка события в первую очередь полезна при работе с большими объемами данных, чтобы избежать снижения производительности при установке значения строки ContextMenuStrip для нескольких строк. Подробнее см. в разделе Масштабирование элемента управления DataGridView в Windows Forms.

Изменение этого свойства вызывает RowContextMenuStripChanged событие на владельце DataGridView, если оно существует.

Если текущая строка является общей, используйте GetContextMenuStrip метод , а не получение значения этого свойства.

Применяется к

См. также раздел