Right click and select datagridview row

I have a datagridview with a context menu strip attached. When a user selects a row and right clicks they get a menu to perform a task. Why do they have to left click a row to select before right clicking to perform the menu task. How do i fix this?
LVL 13
wiswalldAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jorge PaulinoIT Pro/DeveloperCommented:
Hi wiswalld,

Do you have the context menu set it on the datagridview properties ?
0
wiswalldAuthor Commented:
Yes

This is the code I run with one of the menu items from the context menu strip:

 Private Sub AssignUnitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AssignUnitToolStripMenuItem.Click

        Dim dr As DataRow = Me._CAD_050107DataSet.Tables("assignedvehicles").NewRow
        'Put values into row
        dr(1) = EventNumber.Text
        dr(2) = DataGridView1.CurrentRow.Cells(5).Value.ToString
        dr(3) = DataGridView1.CurrentRow.Cells(2).Value.ToString
        dr(4) = DataGridView1.CurrentRow.Cells(3).Value.ToString
        Me.DataGridView1.CurrentRow.Cells(7).Value = "No"
        Me.DataGridView1.CurrentRow.Cells(7).Style.BackColor() = Color.Red
        'and so on, making sure you put values in any ...
        '... fields/columns that do not allow null
        Me._CAD_050107DataSet.Tables("assignedvehicles").Rows.Add(dr)
        Me.DataGridView1.CurrentRow.Cells(7).Value = "No"
        Me.DataGridView1.CurrentRow.Cells(7).Style.BackColor() = Color.Red
        Me.Validate()
        Me.AssignedVehiclesBindingSource.EndEdit()
        Me.DataGridView2.EndEdit()
        Me.AssignedVehiclesTableAdapter.Update(Me._CAD_050107DataSet.AssignedVehicles)
        UpdateDataBase()








    End Sub
0
Jorge PaulinoIT Pro/DeveloperCommented:
Well normally, without any code, you cannot select a datagridview cell with the right click. So you have to select first the cell and then call the contex menu.

Try this:

    Private Sub DataGridView1_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseUp
        If e.Button = Windows.Forms.MouseButtons.Right Then

            Dim hti As DataGridView.HitTestInfo = DataGridView1.HitTest(e.X, e.Y)
            If hti.Type = DataGridViewHitTestType.Cell And hti.RowIndex >= 0 Then

                ' Selects the datagridview cell
                DataGridView1.CurrentCell = DataGridView1(hti.ColumnIndex, hti.RowIndex)

                ' Show the context menu
                ContextMenuStrip1.Show(Me.DataGridView1, New Point(e.X, e.Y))

            End If

        End If
    End Sub
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

wiswalldAuthor Commented:
Shows menu strip but does not hightlight row.
0
Jorge PaulinoIT Pro/DeveloperCommented:
>> Shows menu strip but does not hightlight row.
But hightlight the cell, right ?
0
wiswalldAuthor Commented:
Yes. I didn't try that. I am trying to figure out how to highlight the row by right clicking the datagridview border. Is that possible?
0
Jorge PaulinoIT Pro/DeveloperCommented:
Sure:

 Private Sub DataGridView1_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseUp
        If e.Button = Windows.Forms.MouseButtons.Right Then

            Dim hti As DataGridView.HitTestInfo = DataGridView1.HitTest(e.X, e.Y)
            If hti.Type = DataGridViewHitTestType.RowHeader And hti.RowIndex >= 0 Then

                ' Selects the datagridview row
                DataGridView1.Rows(hti.RowIndex).Selected = True

                ' Show the context menu
                ContextMenuStrip1.Show(Me.DataGridView1, New Point(e.X, e.Y))

            End If

        End If
    End Sub
0
wiswalldAuthor Commented:
The only problem I have is when I open the form the first row first cell is highlighted and if I right click the second row it highlights fine but copies the first row not the second row.
0
Jorge PaulinoIT Pro/DeveloperCommented:
Ok I see ... no problem. Try this:

 Private Sub DataGridView1_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseUp
        If e.Button = Windows.Forms.MouseButtons.Right Then

            Dim hti As DataGridView.HitTestInfo = DataGridView1.HitTest(e.X, e.Y)
            If hti.Type = DataGridViewHitTestType.RowHeader And hti.RowIndex >= 0 Then

               ' Clears other selections
                For Each row As DataGridViewRow In DataGridView1.Rows
                    DataGridView1.Rows(row.Index).Selected = False
                Next

                ' Selects the datagridview row
                DataGridView1.Rows(hti.RowIndex).Selected = True

                ' Show the context menu
                ContextMenuStrip1.Show(Me.DataGridView1, New Point(e.X, e.Y))

            End If

        End If
    End Sub
0
wiswalldAuthor Commented:
Getting really warm. Highlight the selected row without highlighting the first cell in the first row but still copies the first row unless I left click the second row first.

I can hide the row header and just use the first suggestion but was trying to avoid that.
0
Jorge PaulinoIT Pro/DeveloperCommented:
>> Getting really warm. Highlight the selected row without highlighting the first cell in the first row but still copies the first row unless I left click the second row first.

thats probably because that cell is in edit mode.

Add this before the for each loop

  DataGridView1.EndEdit()
0
Jorge PaulinoIT Pro/DeveloperCommented:
Sorry I have to leave now for some hours. I will check latter if it's already solved or if you still need help.
0
wiswalldAuthor Commented:
>>Add this before the for each loop


Not sure what you mean.
0
wiswalldAuthor Commented:
I am going to bed. Check back tomorrow.
0
Jorge PaulinoIT Pro/DeveloperCommented:
This way:

Private Sub DataGridView1_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseUp
        If e.Button = Windows.Forms.MouseButtons.Right Then

            Dim hti As DataGridView.HitTestInfo = DataGridView1.HitTest(e.X, e.Y)
            If hti.Type = DataGridViewHitTestType.RowHeader And hti.RowIndex >= 0 Then

                DataGridView1.EndEdit()

               ' Clears other selections
                For Each row As DataGridViewRow In DataGridView1.Rows
                    DataGridView1.Rows(row.Index).Selected = False
                Next

                ' Selects the datagridview row
                DataGridView1.Rows(hti.RowIndex).Selected = True

                ' Show the context menu
                ContextMenuStrip1.Show(Me.DataGridView1, New Point(e.X, e.Y))

            End If

        End If
    End Sub
0
wiswalldAuthor Commented:
It is succesfully highlighting the row I want with a right click but still copying the first row not the selected row.
0
wiswalldAuthor Commented:
I appreciate the help but looks like I may have to go with the first choice and eliminate the row header and select the cell. Didn't really want to do that.
0
ab_khadilkarCommented:
This is code for c#

This works, although you might need some more error-checking and it only selects the cell  It also assign context menu to that cell

But, here's what I did. In the event handler for the Grid's CellMouseDown event, put this code (hopefully you won't mind  C# code here ... it should be an easy translation for you):
private void DataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
 
ContextMenu.Show(DataGridView1, new Point(e.RowIndex, e.ColumnIndex));
 
}

Open in new window

0
Reset_Commented:
a bit dirty perhaps but it does the trick :)

The problem is that the vb.code that is accepted as the solution always return rowindex 0. If you do a select on a cell the row index gets updated.
If e.Button = Windows.Forms.MouseButtons.Right Then
            Dim hti As DataGridView.HitTestInfo = sender.HitTest(e.X, e.Y)
            If hti.Type = DataGridViewHitTestType.Cell Then
                'MsgBox("HTI.type = Cell")
                If Not Me.NoderDataGridView.Rows(hti.RowIndex).Selected Then

                    ' User right clicked a row that is not selected, so throw away all other selections and select this row
                    Me.NoderDataGridView.EndEdit()
                    Me.NoderDataGridView.ClearSelection()

                    Me.NoderDataGridView.Rows(hti.RowIndex).Selected = True

                    NoderDataGridView.Rows(hti.RowIndex).Cells(2).Selected = True
                    NoderDataGridView.Rows(hti.RowIndex).Cells(3).Selected = True
                    NoderDataGridView.Rows(hti.RowIndex).Cells(2).Selected = True
                    

                End If

            End If

        End If

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.