derecho contextual c# select datagridview contextmenu right-click

contextual - menu click derecho c#



Haga clic con el botón derecho para seleccionar una fila en una vista de tabla de datos y muestre un menú para eliminarla (10)

Tengo pocas columnas en mi DataGridView, y hay datos en mis filas. Vi algunas soluciones aquí, ¡pero no puedo combinarlas!

Simplemente una forma de hacer clic derecho en una fila, seleccionará toda la fila y mostrará un menú con una opción para eliminar la fila y cuando la opción seleccionada borre la fila.

Hice algunos intentos pero ninguno funciona y parece desordenado. ¿Que debería hacer?


Es mucho más fácil agregar solo el evento para mousedown:

private void MyDataGridView_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { var hti = MyDataGridView.HitTest(e.X, e.Y); MyDataGridView.Rows[hti.RowIndex].Selected = true; MyDataGridView.Rows.RemoveAt(rowToDelete); MyDataGridView.ClearSelection(); } }

Esto es más fácil. Por supuesto, debes iniciar tu mousedown-event como ya se mencionó con:

this.MyDataGridView.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MyDataGridView_MouseDown);

en tu constructor


Finalmente lo resolví:

  • En Visual Studio, crea un ContextMenuStrip con un elemento llamado "DeleteRow"

  • Luego, en el enlace DataGridView, ContextMenuStrip

Usar el siguiente código me ayudó a hacerlo funcionar.

this.MyDataGridView.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MyDataGridView_MouseDown); this.DeleteRow.Click += new System.EventHandler(this.DeleteRow_Click);

Aquí está la parte genial

private void MyDataGridView_MouseDown(object sender, MouseEventArgs e) { if(e.Button == MouseButtons.Right) { var hti = MyDataGridView.HitTest(e.X, e.Y); MyDataGridView.ClearSelection(); MyDataGridView.Rows[hti.RowIndex].Selected = true; } } private void DeleteRow_Click(object sender, EventArgs e) { Int32 rowToDelete = MyDataGridView.Rows.GetFirstRow(DataGridViewElementStates.Selected); MyDataGridView.Rows.RemoveAt(rowToDelete); MyDataGridView.ClearSelection(); }


Para completar esta pregunta, mejor utilizar un evento Grid en lugar de un mouse.

Primero configure sus propiedades de cuadrícula de datos:

SelectionMode a FullRowSelect y RowTemplate / ContextMenuStrip a un menú contextual.

Crear el evento CellMouseDown: -

private void myDatagridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) { if (e.Button == MouseButtons.Right) { int rowSelected = e.RowIndex; if (e.RowIndex != -1) { this.myDatagridView.Rows[rowSelected].Selected = true; } // you now have the selected row with the context menu showing for the user to delete etc. } }


También puede hacer esto un poco más simple usando lo siguiente dentro del código del evento:

private void MyDataGridView_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { rowToDelete = e.RowIndex; MyDataGridView.Rows.RemoveAt(rowToDelete); MyDataGridView.ClearSelection(); } }


Tengo una nueva solución que viene en el mismo resultado, pero con menos código. para Winforms ... Ese es el ejemplo en portugués Seguimiento paso a paso

  1. Crea un contextMenuStrip en tu formulario y crea un elemento
  2. Firme un clic de evento (OnCancelarItem_Click) para este contextoMenuStrip
  3. Crear un evento ''UserDeletingRow'' en gridview y ahora ... has simulado en key press del from user

    no olvides habilitar eliminar en la vista de cuadrícula, ¿no?

y finalmente...


Todas las respuestas planteadas en esta pregunta se basan en un evento de clic del mouse. También puede asignar un ContenxtMenuStrip a su DataGridview y comprobar si hay una fila seleccionada cuando el usuario RightMouseButtons en el DataGridView y decidir si desea ver el ContenxtMenuStrip o no. Puede hacerlo configurando el valor CancelEventArgs.Cancel en el evento de apertura de ContextMenuStrip

private void MyContextMenuStrip_Opening(object sender, CancelEventArgs e) { //Only show ContextMenuStrip when there is 1 row selected. if (MyDataGridView.SelectedRows.Count != 1) e.Cancel = true; }

Pero si tiene varias tiras de menús contextuales, cada una con diferentes opciones, dependiendo de la selección, me gustaría hacer un clic con el mouse también.


Vea aquí que se puede hacer usando la propiedad DataGridView RowTemplate .

Nota: Este código no está probado pero he usado este método antes.

// Create DataGridView DataGridView gridView = new DataGridView(); gridView.AutoGenerateColumns = false; gridView.Columns.Add("Col", "Col"); // Create ContextMenu and set event ContextMenuStrip cMenu = new ContextMenuStrip(); ToolStripItem mItem = cMenu.Items.Add("Delete"); mItem.Click += (o, e) => { /* Do Something */ }; // This makes all rows added to the datagridview use the same context menu DataGridViewRow defaultRow = new DataGridViewRow(); defaultRow.ContextMenuStrip = cMenu;

Y ahí tienes, tan fácil como eso!


base en la respuesta @ Data-Base no funcionará hasta que haga el modo de selección FullRow

MyDataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

pero si necesitas hacer que funcione en el modo CellSelect

MyDataGridView.SelectionMode = DataGridViewSelectionMode.CellSelect; // for cell selection private void MyDataGridView_MouseDown(object sender, MouseEventArgs e) { if(e.Button == MouseButtons.Right) { var hit = MyDataGridView.HitTest(e.X, e.Y); MyDataGridView.ClearSelection(); // cell selection MyDataGridView[hit.ColumnIndex,hit.RowIndex].Selected = true; } } private void DeleteRow_Click(object sender, EventArgs e) { int rowToDelete = MyDataGridView.Rows.GetFirstRow(DataGridViewElementStates.Selected); MyDataGridView.Rows.RemoveAt(rowToDelete); MyDataGridView.ClearSelection(); }


private void MyDataGridView_MouseDown(object sender, MouseEventArgs e) { if(e.Button == MouseButtons.Right) { MyDataGridView.ClearSelection(); MyDataGridView.Rows[e.RowIndex].Selected = true; } } private void DeleteRow_Click(object sender, EventArgs e) { Int32 rowToDelete = MyrDataGridView.Rows.GetFirstRow(DataGridViewElementStates.Selected); MyDataGridView.Rows.RemoveAt(rowToDelete); MyDataGridView.ClearSelection(); }


private void dgvOferty_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e) { dgvOferty.ClearSelection(); int rowSelected = e.RowIndex; if (e.RowIndex != -1) { this.dgvOferty.Rows[rowSelected].Selected = true; } e.ContextMenuStrip = cmstrip; }

TADA: D. El período más fácil. Para las celdas personalizadas simplemente modifique un poco.