Exportar (0) Imprimir
Expandir Tudo
Expandir Minimizar
Este artigo foi traduzido por máquina. Coloque o ponteiro do mouse sobre as frases do artigo para ver o texto original. Mais informações.
Tradução
Original
Este tópico ainda não foi avaliado como - Avalie este tópico

DataGridViewCellContextMenuStripNeededEventHandler Representante

Represents the method that will handle a CellContextMenuStripNeeded event of a DataGridView.

Namespace:  System.Windows.Forms
Assembly:  System.Windows.Forms (em System.Windows.Forms. dll)
public delegate void DataGridViewCellContextMenuStripNeededEventHandler(
	Object sender,
	DataGridViewCellContextMenuStripNeededEventArgs e
)

The CellContextMenuStripNeeded event occurs only when the DataGridView control DataSource property is set or its VirtualMode property is true.

When you handle the CellContextMenuStripNeeded event, the shortcut menu that you specify in the handler is shown whenever the user right-clicks a cell.Isso é útil quando você deseja exibir menus de atalho determinados pelo estado atual ou valor de uma célula.

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.

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.This property is initialized with the value of the cell ContextMenuStrip property, which the event value overrides.

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.Para obter mais informações, consulte Práticas recomendadas para escala o controle DataGridView do Windows Forms.

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.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.You can specify null for a cell shortcut menu, however, to prevent a row shortcut menu from being overridden.

Para obter mais informações sobre tratamento de eventos, consulte Consumindo Eventos.

When you create a DataGridViewCellContextMenuStripNeededEventHandler delegate, you identify the method that will handle the event.Para associar o evento com o manipulador de eventos, adicione uma instância do delegate ao evento.O manipulador de evento é chamado sempre que o evento ocorre, a menos que você remova o delegate.Para obter mais informações sobre delegates de manipulador de eventos, consulte Eventos e representantes.

The following code example uses DataGridViewCellContextMenuStripNeededEventArgs to set the context menu without unsharing the row.

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();
}


Isso foi útil para você?
(1500 caracteres restantes)
Agradecemos os seus comentários

Contribuições da comunidade

ADICIONAR
Mostrar:
© 2014 Microsoft. Todos os direitos reservados.