Datagridview - focus on the cell that was right-clicked

I have a datagridview that I have included ContextMenuStrip1. I would like it to delete a row in a datagridview when the row was right-clicked and they click delete row. Uninstall works for me, and the menu appears, but it does not work when you right-click on a datagridview.

Here I set the line for editing:

Private Sub ModifyRowToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ModifyRowToolStripMenuItem.Click If Not datagridview_TagAssignment.CurrentRow Is Nothing Then datagridview_TagAssignment.CurrentCell = datagridview_TagAssignment.Item(0, datagridview_TagAssignment.CurrentRow.Index) datagridview_TagAssignment.BeginEdit(True) End If End Sub 

I always end up on line (0) and never right clicked.

  Private Sub datagridview_TagAssignment_CellMouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles datagridview_TagAssignment.CellMouseClick If e.Button = Windows.Forms.MouseButtons.Right AndAlso e.RowIndex >= 0 Then datagridview_TagAssignment.Rows(e.RowIndex).Selected = True End If End Sub 

Anyone have any suggestions?

+4
source share
1 answer
 Private Sub DataGridView1_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseClick If e.Button = Windows.Forms.MouseButtons.Right Then rowClicked = DataGridView1.HitTest(e.Location.X, e.Location.Y).RowIndex ContextMenuStrip1.Items.Add(rowClicked.ToString) ContextMenuStrip1.Show(DataGridView1, e.Location) ContextMenuStrip1.Items.Clear() End If End Sub 

Edit: updated to handle the context menu bar.

This should give you the row row index by right-clicking with the mouse coordinates. Which should allow you to delete a row based on knowledge of the index.

Edit

This is my code in your comment.

I have a solution with WinForm with the addition of a DataGridView. and this is the code in the form.

 Public Class Form1 Dim bindS As New BindingSource Dim rowClicked As Integer Private Sub DataGridView1_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseClick If e.Button = Windows.Forms.MouseButtons.Right Then rowClicked = DataGridView1.HitTest(e.Location.X, e.Location.Y).RowIndex ContextMenuStrip1.Items.Add(rowClicked.ToString) ContextMenuStrip1.Show(DataGridView1, e.Location) ContextMenuStrip1.Items.Clear() End If End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim s As New List(Of String) s.Add("String one") s.Add("String Two") bindS.DataSource = s DataGridView1.DataSource = bindS End Sub End Class 

Right clicking on a row shows the correct row index

Make sure the event arguments you are processing are System.Windows.Forms.MouseEventArgs , I noticed that you are processing a cell click

+5
source

Source: https://habr.com/ru/post/1305227/


All Articles