我有一个datagridview,我已经打开了ContextMenuStrip1。我想在右键单击行时删除datagridview中的一行,然后单击“删除行”。我有删除工作,菜单显示,但是当您右键单击datagridview时,这不会触发。
这是我将行设置为编辑的地方:
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
我总是以行(0)结束,而不是我右键点击的行。
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
有人有任何建议吗?
答案 0 :(得分:5)
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
编辑:已更新以处理上下文菜单条。
这应该为您提供使用鼠标坐标右键单击的行的行索引。哪个应该让你根据知道索引删除行。
修改
根据你对它的评论不起作用这是我的代码
我有一个带有添加了dataGridView的WinForm的解决方案。这是表格中的代码。
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
右键单击一行显示正确的行索引
确保您正在处理的事件参数是System.Windows.Forms.MouseEventArgs
我注意到您正在处理单元格点击