Haga clic derecho para seleccionar una fila en un Datagridview y mostrar un menú para eliminarla
Tengo pocas columnas en mi DataGridView, y hay datos en mis filas. He visto pocas 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 eliminará la fila.
Hice pocos intentos, pero ninguno funciona y se ve desordenado. ¿Qué debo hacer?
10 answers
Finalmente lo resolví:
-
En Visual Studio, cree un ContextMenuStrip con un elemento llamado"deleteRow"
-
A continuación, en el enlace DataGridView el ContextMenuStrip
Usar el siguiente código me ayudó a que funcionara.
this.MyDataGridView.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MyDataGridView_MouseDown);
this.DeleteRow.Click += new System.EventHandler(this.DeleteRow_Click);
Aquí está la parte fresca
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();
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-08 15:31:54
Para completar esta pregunta, es mejor usar un evento de cuadrícula en lugar de mouse.
Primero Establezca las propiedades de la cuadrícula de datos:
SelectionMode to FullRowSelect y RowTemplate / ContextMenuStrip a un menú contextual.
Crea 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.
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-03-22 12:06:54
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 de la manera más fácil. Para las celdas personalizadas solo modifique un poco.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-05 11:11:31
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, debe iniciar su evento mousedown como ya se mencionó con:
this.MyDataGridView.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MyDataGridView_MouseDown);
En su constructor.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-26 12:11:02
Todas las respuestas planteadas en esta pregunta se basan en un evento de clic del ratón. También puede asignar un ContenxtMenuStrip
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 estableciendo el valor CancelEventArgs.Cancel
en el evento de apertura del 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ú contextual, con cada una conteniendo diferentes opciones, dependiendo de la selección, yo iría por un clic del ratón-enfoque yo también.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-28 12:52:36
Base en @Respuesta de la base de datos no funcionará hasta que haga el modo de selección FullRow
MyDataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
Pero si necesita hacerlo funcionar en 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();
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-29 18:25:45
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();
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-26 12:10:11
También puede hacer esto un poco más simple utilizando lo siguiente dentro del código de evento:
private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
rowToDelete = e.RowIndex;
MyDataGridView.Rows.RemoveAt(rowToDelete);
MyDataGridView.ClearSelection();
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-14 20:28:54
Ver aquí se puede hacer usando el DataGridView
RowTemplate
propiedad.
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í lo tienes, ¡tan fácil como eso!
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-04 06:08:29
Tengo una nueva solución alternativa que viene con el mismo resultado, pero con menos código. para Winforms... El ejemplo es in portuguese Seguimiento paso a paso
- Crea un ContextMenuStrip en tu formulario y crea un elemento
- Firme un clic de evento (OnCancelarItem_Click) para este ContextMenuStrip
- Crear un evento 'UserDeletingRow' en gridview
y ahora... has simulado al pulsar la tecla supr del usuario
No te olvides de habilitar borrar en el gridview, ¿verdad?!
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-02 23:47:00