共用方式為


DataGridView.RowContextMenuStripNeeded 事件

定義

發生於需要資料列的捷徑功能表時。

public:
 event System::Windows::Forms::DataGridViewRowContextMenuStripNeededEventHandler ^ RowContextMenuStripNeeded;
public event System.Windows.Forms.DataGridViewRowContextMenuStripNeededEventHandler RowContextMenuStripNeeded;
public event System.Windows.Forms.DataGridViewRowContextMenuStripNeededEventHandler? RowContextMenuStripNeeded;
member this.RowContextMenuStripNeeded : System.Windows.Forms.DataGridViewRowContextMenuStripNeededEventHandler 
Public Custom Event RowContextMenuStripNeeded As DataGridViewRowContextMenuStripNeededEventHandler 

事件類型

範例

下列程式代碼範例會處理 事件, RowContextMenuStripNeeded 以根據員工的職稱提供 ContextMenuStrip 。 在此範例中,有兩個快捷功能表,一個用於經理,另一個用於所有其他員工。

void dataGridView1_RowContextMenuStripNeeded(object sender,
    DataGridViewRowContextMenuStripNeededEventArgs e)
{
    DataGridViewRow dataGridViewRow1 = dataGridView1.Rows[e.RowIndex];

    toolStripMenuItem1.Enabled = true;

    // Show the appropriate ContextMenuStrip based on the employees title.
    if ((dataGridViewRow1.Cells["Title"].Value.ToString() ==
        "Sales Manager") ||
        (dataGridViewRow1.Cells["Title"].Value.ToString() ==
        "Vice President, Sales"))
    {
        e.ContextMenuStrip = managerMenuStrip;
    }
    else
    {
        e.ContextMenuStrip = employeeMenuStrip;
    }

    contextMenuRowIndex = e.RowIndex;
}
Public Sub dataGridView1_RowContextMenuStripNeeded( _
    ByVal sender As Object, _
    ByVal e As DataGridViewRowContextMenuStripNeededEventArgs) _
    Handles dataGridView1.RowContextMenuStripNeeded

    Dim dataGridViewRow1 As DataGridViewRow = _
    dataGridView1.Rows(e.RowIndex)

    toolStripMenuItem1.Enabled = True

    ' Show the appropriate ContextMenuStrip based on the employees title.
    If dataGridViewRow1.Cells("Title").Value.ToString() = _
        "Sales Manager" OrElse _
        dataGridViewRow1.Cells("Title").Value.ToString() = _
        "Vice President, Sales" Then

        e.ContextMenuStrip = managerMenuStrip
    Else
        e.ContextMenuStrip = employeeMenuStrip
    End If

    contextMenuRowIndex = e.RowIndex
End Sub

備註

RowContextMenuStripNeeded只有在設定控件DataSource屬性或其 VirtualMode 屬性為 true時,DataGridView才會發生此事件。 RowContextMenuStripNeeded當您想要顯示數據列目前狀態或包含的值所決定的快捷方式功能表時,處理事件很有用。

當您處理 RowContextMenuStripNeeded 事件時,每當使用者以滑鼠右鍵按下數據列時,就會顯示您在處理程式中指定的快捷方式功能表,除非 CellContextMenuStripNeeded 覆寫所單擊特定儲存格的快捷方式選單。

RowContextMenuStripNeeded每當以程式設計方式擷取屬性的值DataGridViewRow.ContextMenuStrip,或使用者以滑鼠右鍵按兩下數據列時,也會發生此事件。

您可以使用 DataGridViewRowContextMenuStripNeededEventArgs.RowIndex 屬性來判斷數據列的狀態或其包含的值,並使用這項資訊來變更或修改 DataGridViewRowContextMenuStripNeededEventArgs.ContextMenuStrip 屬性。 這個屬性會使用事件值所覆寫的數據列 ContextMenuStrip 屬性值初始化。

RowContextMenuStripNeeded處理大量數據時,請處理 事件,以避免設定多個數據列的數據列ContextMenuStrip值效能負面影響。 如需詳細資訊,請參閱 縮放 Windows Form DataGridView 控制項的最佳做法

如需如何處理事件的詳細資訊,請參閱 處理和引發事件

適用於

另請參閱