DataGridViewCellContextMenuStripNeededEventHandler DataGridViewCellContextMenuStripNeededEventHandler DataGridViewCellContextMenuStripNeededEventHandler DataGridViewCellContextMenuStripNeededEventHandler Delegate

Definizione

Rappresenta il metodo che gestirà l'evento CellContextMenuStripNeeded di un oggetto DataGridView.Represents the method that will handle a CellContextMenuStripNeeded event of a DataGridView.

public delegate void DataGridViewCellContextMenuStripNeededEventHandler(System::Object ^ sender, DataGridViewCellContextMenuStripNeededEventArgs ^ e);
public delegate void DataGridViewCellContextMenuStripNeededEventHandler(object sender, DataGridViewCellContextMenuStripNeededEventArgs e);
type DataGridViewCellContextMenuStripNeededEventHandler = delegate of obj * DataGridViewCellContextMenuStripNeededEventArgs -> unit
Public Delegate Sub DataGridViewCellContextMenuStripNeededEventHandler(sender As Object, e As DataGridViewCellContextMenuStripNeededEventArgs)

Parametri

sender
Object Object Object Object

Origine dell'evento.The source of the event.

Ereditarietà
DataGridViewCellContextMenuStripNeededEventHandlerDataGridViewCellContextMenuStripNeededEventHandlerDataGridViewCellContextMenuStripNeededEventHandlerDataGridViewCellContextMenuStripNeededEventHandler

Esempi

Nell'esempio di codice seguente DataGridViewCellContextMenuStripNeededEventArgs viene usato per impostare il menu di scelta rapida senza condividere la riga.The following code example uses DataGridViewCellContextMenuStripNeededEventArgs to set the context menu without unsharing the row.

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

Commenti

L' CellContextMenuStripNeeded evento si verifica solo quando DataGridView la DataSource proprietà del controllo è impostata o se truela relativa VirtualMode proprietà è.The CellContextMenuStripNeeded event occurs only when the DataGridView control DataSource property is set or its VirtualMode property is true.

Quando si gestisce l' CellContextMenuStripNeeded evento, il menu di scelta rapida specificato nel gestore viene visualizzato ogni volta che l'utente fa clic con il pulsante destro del mouse su una cella.When you handle the CellContextMenuStripNeeded event, the shortcut menu that you specify in the handler is shown whenever the user right-clicks a cell. Questa opzione è utile quando si desidera visualizzare i menu di scelta rapida determinati dallo stato corrente o dal valore di una cella.This is useful when you want to display shortcut menus determined by the current state or value of a cell.

L' CellContextMenuStripNeeded evento si verifica anche ogni volta che viene DataGridViewCell.ContextMenuStrip recuperato il valore della proprietà, a livello di codice o quando l'utente fa clic con il pulsante destro del mouse sulla cella.The CellContextMenuStripNeeded event also occurs whenever the value of the DataGridViewCell.ContextMenuStrip property is retrieved, either programmatically or when the user right-clicks the cell.

È possibile utilizzare le ColumnIndex proprietà RowIndex e per determinare lo stato o il valore di una cella e utilizzare queste informazioni per impostare la ContextMenuStrip proprietà.You can use the ColumnIndex and RowIndex properties to determine the state or value of a cell, and use this information to set the ContextMenuStrip property. Questa proprietà viene inizializzata con il valore della proprietà ContextMenuStrip della cella, che sostituisce il valore dell'evento.This property is initialized with the value of the cell ContextMenuStrip property, which the event value overrides.

Gestire l' CellContextMenuStripNeeded evento quando si lavora con grandi quantità di dati per evitare le penalizzazioni delle prestazioni dell' ContextMenuStrip impostazione del valore della cella per più celle.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. Per altre informazioni, vedere Procedure consigliate per ridimensionare il controllo DataGridView Windows Form.For more information, see Best Practices for Scaling the Windows Forms DataGridView Control.

È anche possibile specificare i menu di scelta rapida per le singole righe anziché per le singole ContextMenuStrip celle impostando la DataGridView proprietà Row RowContextMenuStripNeeded o gestendo l'evento del controllo.You can also specify shortcut menus for individual rows rather than individual cells by setting the row ContextMenuStrip property or handling the DataGridView control's RowContextMenuStripNeeded event. L'impostazione ContextMenuStrip della proprietà della cella sostituisce ContextMenuStrip l'impostazione della proprietà Row CellContextMenuStripNeeded e l'evento sostituisce RowContextMenuStripNeeded l'impostazione della proprietà ContextMenuStrip Event e Row.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. Tuttavia, è null possibile specificare per un menu di scelta rapida della cella per impedire l'override di un menu di scelta rapida della riga.You can specify null for a cell shortcut menu, however, to prevent a row shortcut menu from being overridden.

Per altre informazioni su come gestire gli eventi, vedere la gestione e generazione di eventi.For more information about how to handle events, see Handling and Raising Events.

Quando si crea un delegato DataGridViewCellContextMenuStripNeededEventHandler, si identifica il metodo che gestirà l'evento.When you create a DataGridViewCellContextMenuStripNeededEventHandler delegate, you identify the method that will handle the event. Per associare l'evento al gestore eventi in uso, aggiungere all'evento un'istanza del delegato.To associate the event with your event handler, add an instance of the delegate to the event. Il gestore eventi viene chiamato ogni volta che si verifica l'evento, a meno che non venga rimosso il delegato.The event handler is called whenever the event occurs, unless you remove the delegate. Per ulteriori informazioni sui delegati del gestore eventi, vedere gestione e generazione di eventi.For more information about event-handler delegates, see Handling and Raising Events.

Metodi di estensione

GetMethodInfo(Delegate) GetMethodInfo(Delegate) GetMethodInfo(Delegate) GetMethodInfo(Delegate)

Ottiene un oggetto che rappresenta il metodo rappresentato dal delegato specificato.Gets an object that represents the method represented by the specified delegate.

Si applica a

Vedi anche