DataGridView.CellContextMenuStripNeeded DataGridView.CellContextMenuStripNeeded DataGridView.CellContextMenuStripNeeded DataGridView.CellContextMenuStripNeeded Event

정의

셀의 바로 가기 메뉴가 필요할 때 발생합니다.Occurs when a cell's shortcut menu is needed.

public:
 event System::Windows::Forms::DataGridViewCellContextMenuStripNeededEventHandler ^ CellContextMenuStripNeeded;
public event System.Windows.Forms.DataGridViewCellContextMenuStripNeededEventHandler CellContextMenuStripNeeded;
member this.CellContextMenuStripNeeded : System.Windows.Forms.DataGridViewCellContextMenuStripNeededEventHandler 
Public Custom Event CellContextMenuStripNeeded As DataGridViewCellContextMenuStripNeededEventHandler 

예제

다음 코드 예제를 사용 하는 방법에 설명 된 CellContextMenuStripNeeded 셀을 마우스 오른쪽 단추로 클릭할 때 사용 되는 사용자 지정 바로 가기 메뉴를 표시 하려면 이벤트 처리기입니다.The following code example demonstrates how to use a CellContextMenuStripNeeded event handler to display a custom shortcut menu used when the user right-clicks a cell.

ToolStripMenuItem^ wholeTable;
ToolStripMenuItem^ lookUp;
System::Windows::Forms::ContextMenuStrip^ strip;
String^ cellErrorText;

void dataGridView1_CellContextMenuStripNeeded( Object^ /*sender*/,
    DataGridViewCellContextMenuStripNeededEventArgs^ e )
{
    cellErrorText = String::Empty;
    if ( strip == nullptr )
    {
        strip = gcnew System::Windows::Forms::ContextMenuStrip;
        lookUp->Text = L"Look Up";
        wholeTable->Text = L"See Whole Table";
        strip->Items->Add( lookUp );
        strip->Items->Add( wholeTable );
    }

    e->ContextMenuStrip = strip;
}

void wholeTable_Click( Object^ /*sender*/, EventArgs^ /*e*/ )
{
    dataGridView1->DataSource = Populate( L"Select * from employees", true );
}

DataGridViewCellEventArgs^ theCellImHoveringOver;
void dataGridView1_CellMouseEnter( Object^ /*sender*/, DataGridViewCellEventArgs^ e )
{
    theCellImHoveringOver = e;
}

DataGridViewCellEventArgs^ cellErrorLocation;
void lookUp_Click( Object^ /*sender*/, EventArgs^ /*e*/ )
{
    try
    {
        dataGridView1->DataSource = Populate( String::Format( L"Select * from employees where {0} = '{1}'", dataGridView1->Columns[ theCellImHoveringOver->ColumnIndex ]->Name, dataGridView1->Rows[ theCellImHoveringOver->RowIndex ]->Cells[ theCellImHoveringOver->ColumnIndex ]->Value ), true );
    }
    catch ( ... ) 
    {
        cellErrorText = L"Can't look this cell up";
        cellErrorLocation = theCellImHoveringOver;
    }

}

void dataGridView1_CellErrorTextNeeded( Object^ /*sender*/, DataGridViewCellErrorTextNeededEventArgs^ e )
{
    if ( cellErrorLocation != nullptr )
    {
        if ( e->ColumnIndex == cellErrorLocation->ColumnIndex && e->RowIndex == cellErrorLocation->RowIndex )
        {
            e->ErrorText = cellErrorText;
        }
    }
}

DataTable^ Populate( String^ query, bool resetUnsharedCounter )
{
    if ( resetUnsharedCounter )
    {
        ResetCounter();
    }


    // Alter the data source as necessary
    SqlDataAdapter^ adapter = gcnew SqlDataAdapter( query,
        gcnew SqlConnection( L"Integrated Security=SSPI;Persist Security Info=False;"
        L"Initial Catalog=Northwind;Data Source= localhost" ) );
    DataTable^ table = gcnew DataTable;
    adapter->Fill( table );
    return table;
}

Label^ count;
int unsharedRowCounter;
void ResetCounter()
{
    unsharedRowCounter = 0;
    count->Text = unsharedRowCounter.ToString();
}
private ToolStripMenuItem wholeTable = new ToolStripMenuItem();
private ToolStripMenuItem lookUp = new ToolStripMenuItem();
private ContextMenuStrip strip;
private string cellErrorText;

private void dataGridView1_CellContextMenuStripNeeded(object sender,
    DataGridViewCellContextMenuStripNeededEventArgs e)
{
    cellErrorText = String.Empty;

    if (strip == null)
    {
        strip = new ContextMenuStrip();
        lookUp.Text = "Look Up";
        wholeTable.Text = "See Whole Table";
        strip.Items.Add(lookUp);
        strip.Items.Add(wholeTable);
    }
    e.ContextMenuStrip = strip;
}

private void wholeTable_Click(object sender, EventArgs e)
{
    dataGridView1.DataSource = Populate("Select * from employees", true);
}

private DataGridViewCellEventArgs theCellImHoveringOver;

private void dataGridView1_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
{
    theCellImHoveringOver = e;
}

private DataGridViewCellEventArgs cellErrorLocation;

private void lookUp_Click(object sender, EventArgs e)
{
    try
    {
        dataGridView1.DataSource = Populate("Select * from employees where " +
            dataGridView1.Columns[theCellImHoveringOver.ColumnIndex].Name + " = '" +
            dataGridView1.Rows[theCellImHoveringOver.RowIndex].
            Cells[theCellImHoveringOver.ColumnIndex].Value + "'",
            true);
    }
    catch (SqlException)
    {
        cellErrorText = "Can't look this cell up";
        cellErrorLocation = theCellImHoveringOver;
    }
}

private void dataGridView1_CellErrorTextNeeded(object sender,
    DataGridViewCellErrorTextNeededEventArgs e)
{
    if (cellErrorLocation != null)
    {
        if (e.ColumnIndex == cellErrorLocation.ColumnIndex &&
            e.RowIndex == cellErrorLocation.RowIndex)
        {
            e.ErrorText = cellErrorText;
        }
    }
}

private DataTable Populate(string query, bool resetUnsharedCounter)
{
    if (resetUnsharedCounter)
    {
        ResetCounter();
    }

    // Alter the data source as necessary
    SqlDataAdapter adapter = new SqlDataAdapter(query,
        new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;" +
        "Initial Catalog=Northwind;Data Source=localhost"));

    DataTable table = new DataTable();
    table.Locale = System.Globalization.CultureInfo.InvariantCulture;
    adapter.Fill(table);
    return table;
}

private Label count = new Label();
private int unsharedRowCounter;

private void ResetCounter()
{
    unsharedRowCounter = 0;
    count.Text = unsharedRowCounter.ToString();
}
Private WithEvents wholeTable As New ToolStripMenuItem()
Private WithEvents lookUp As New ToolStripMenuItem()
Private strip As ContextMenuStrip
Private cellErrorText As String

Private Sub dataGridView1_CellContextMenuStripNeeded(ByVal sender As Object, _
    ByVal e As DataGridViewCellContextMenuStripNeededEventArgs) _
    Handles dataGridView1.CellContextMenuStripNeeded

    cellErrorText = String.Empty

    If strip Is Nothing Then
        strip = New ContextMenuStrip()
        lookUp.Text = "Look Up"
        wholeTable.Text = "See Whole Table"
        strip.Items.Add(lookUp)
        strip.Items.Add(wholeTable)
    End If
    e.ContextMenuStrip = strip
End Sub

Private Sub wholeTable_Click(ByVal sender As Object, ByVal e As EventArgs) Handles wholeTable.Click
    dataGridView1.DataSource = Populate("Select * from employees", True)
End Sub

Private theCellImHoveringOver As DataGridViewCellEventArgs

Private Sub dataGridView1_CellMouseEnter(ByVal sender As Object, _
    ByVal e As DataGridViewCellEventArgs) _
    Handles dataGridView1.CellMouseEnter

    theCellImHoveringOver = e
End Sub

Private cellErrorLocation As DataGridViewCellEventArgs

Private Sub lookUp_Click(ByVal sender As Object, ByVal e As EventArgs) Handles lookUp.Click
    Try
        dataGridView1.DataSource = Populate("Select * from employees where " & _
            dataGridView1.Columns(theCellImHoveringOver.ColumnIndex).Name & " = '" & _
            dataGridView1.Rows(theCellImHoveringOver.RowIndex).Cells(theCellImHoveringOver.ColumnIndex).Value.ToString() & _
            "'", True)
    Catch ex As SqlException
        cellErrorText = "Can't look this cell up"
        cellErrorLocation = theCellImHoveringOver
    End Try
End Sub

Private Sub dataGridView1_CellErrorTextNeeded(ByVal sender As Object, _
            ByVal e As DataGridViewCellErrorTextNeededEventArgs) _
            Handles dataGridView1.CellErrorTextNeeded
    If (Not cellErrorLocation Is Nothing) Then
        If e.ColumnIndex = cellErrorLocation.ColumnIndex AndAlso _
            e.RowIndex = cellErrorLocation.RowIndex Then
            e.ErrorText = cellErrorText
        End If
    End If
End Sub

Private Function Populate(ByVal query As String, ByVal resetUnsharedCounter As Boolean) As DataTable

    If resetUnsharedCounter Then
        ResetCounter()
    End If

    ' Alter the data source as necessary
    Dim adapter As New SqlDataAdapter(query, _
        New SqlConnection("Integrated Security=SSPI;Persist Security Info=False;" & _
        "Initial Catalog=Northwind;Data Source=localhost"))

    Dim table As New DataTable()
    table.Locale = System.Globalization.CultureInfo.InvariantCulture
    adapter.Fill(table)
    Return table
End Function

Private count As New Label()
Private unsharedRowCounter As Integer

Private Sub ResetCounter()
    unsharedRowCounter = 0
    count.Text = unsharedRowCounter.ToString()
End Sub

설명

CellContextMenuStripNeeded 이벤트에만 발생 경우를 DataGridView 컨트롤 DataSource 속성을 설정 또는 해당 VirtualMode 속성은 true합니다.The CellContextMenuStripNeeded event occurs only when the DataGridView control DataSource property is set or its VirtualMode property is true.

처리 하는 경우는 CellContextMenuStripNeeded 이벤트 처리기에서 지정 하는 바로 가기 메뉴가 표시 됩니다 사용자 셀을 마우스 오른쪽 단추로 클릭할 때마다 합니다.When you handle the CellContextMenuStripNeeded event, the shortcut menu that you specify in the handler is shown whenever the user right-clicks a cell. 현재 상태 또는 셀의 값에 의해 결정 된 바로 가기 메뉴를 표시 하려는 경우에 유용 합니다.This is useful when you want to display a shortcut menu determined by the current state or value of a cell.

CellContextMenuStripNeeded 이벤트는 또한 될 때마다 발생의 값을 DataGridViewCell.ContextMenuStrip 속성은 검색 하거나 프로그래밍 방식으로 또는 사용자 셀을 마우스 오른쪽 단추로 클릭할 때입니다.The CellContextMenuStripNeeded event also occurs whenever the value of the DataGridViewCell.ContextMenuStrip property is retrieved, either programmatically or when the user right-clicks a cell.

사용할 수는 DataGridViewCellEventArgs.ColumnIndexRowIndex 속성은 셀의 값을 상태를 확인 하 고이 정보를 사용 하 여 변경 하거나 수정 하는 DataGridViewCellContextMenuStripNeededEventArgs.ContextMenuStrip 속성입니다.You can use the DataGridViewCellEventArgs.ColumnIndex and RowIndex properties to determine the state or value of a cell, and use this information to change or modify the DataGridViewCellContextMenuStripNeededEventArgs.ContextMenuStrip property. 이 속성은 셀의 값을 사용 하 여 초기화 ContextMenuStrip 이벤트 값을 재정의 하는 속성입니다.This property is initialized with the value of the cell ContextMenuStrip property, which the event value overrides.

처리를 CellContextMenuStripNeeded 많은 양의 데이터로 작업할 때 이벤트 ContextMenuStrip 여러 셀에 대 한 값입니다.Handle the CellContextMenuStripNeeded event when working with large amounts of data to avoid the performance penalties of setting the cell ContextMenuStrip value for multiple cells. 자세한 내용은 Windows Forms DataGridView 컨트롤의 크기 조정에 대 한 모범 사례합니다.For more information, see Best Practices for Scaling the Windows Forms DataGridView Control.

행을 설정 하 여 개별 셀 대신 개별 행에 대 한 바로 가기 메뉴를 지정할 수도 있습니다 ContextMenuStrip 속성 또는 처리를 RowContextMenuStripNeeded 이벤트입니다.You can also specify shortcut menus for individual rows rather than individual cells by setting the row ContextMenuStrip property or handling the RowContextMenuStripNeeded event. ContextMenuStrip 속성 설정은 행 재정의 ContextMenuStrip 속성 설정 및 CellContextMenuStripNeeded 이벤트 모두를 재정의 합니다 RowContextMenuStripNeeded 이벤트 및 행 ContextMenuStrip 속성 설정.The cell ContextMenuStrip property setting overrides the row ContextMenuStrip property setting, and the CellContextMenuStripNeeded event overrides both the RowContextMenuStripNeeded event and the row ContextMenuStrip property setting. 지정할 수 있습니다 null 덮어쓰기 행 바로 가기 메뉴를 방지 하기 위해 셀 바로 가기 메뉴에 대 한 합니다.However, you can specify null for a cell shortcut menu to prevent a row shortcut menu from being overridden.

이벤트를 처리 하는 방법에 대 한 자세한 내용은 참조 하세요. 이벤트 처리 및 발생합니다.For more information about how to handle events, see Handling and Raising Events.

적용 대상

추가 정보