Thursday, February 8, 2007

Selecting a Data Grid Row with Right Mouse Click in Vb.Net or C#

Clicking on a Datagrid row, with the Right Mouse Button,does not automatically select the clicked row. How can I select the row in a Datagrid that the user clicks with the Right Mouse Button?

Clicking on a row in a Windows Forms Datagrid Row Header, with the Left mouse button, will automatically select the row, but clicking with the right mouse button will not select the row. This can cause confusion and unwanted action by your application if the user is not aware of such action. Additionally, you don't want the user to have to click first with the Left mouse button and then click with the Right mouse button in order to load a context menu.

There is a simple solution that I will describe in this article. First, the code shown below is the MouseUp Event for the Datagrid. If the user clicks on a row header, the event calls the SelectCkBoxRow to select the clicked row. If you want to select the row, regardless of where they click on the row, just remove the test for the "hti.Type = DataGrid.HitTestType.RowHeader".

Private miHitRow As Integer

Private Sub dbgEquipment_MouseUp(ByVal sender As Object, _
ByVal e As System.Windows.Forms.MouseEventArgs) _
Handles dbgEquipment.MouseUp

If e.Button = MouseButtons.Right Then
If hti.Type = DataGrid.HitTestType.RowHeader Then
miHitRow = SelectCkBoxRow(Me.dbgEquipment, e)
End If
End If
End Sub


This function determines the clicked row from the x and y points in the DataGrid where the mouse was clicked. It creates a Point object and uses it to determine the hit row using the DataGrid.HitTestInfo object. It then uses the derived row to select the clicked row.

Public Overloads Function SelectCkBoxRow(ByRef dbg As DataGrid, _
ByVal e As System.Windows.Forms.MouseEventArgs) As Integer
Dim retval As Integer

Try
Dim pt = New Point(e.X, e.Y)
Dim hti As DataGrid.HitTestInfo = dbg.HitTest(pt)

dbg.Select(hti.Row)
Return hti.Row
Catch ex As System.Exception
End Try
End Function



The following code shows the CSharp version of the code:


private int miHitRow;
private void dbgEquipment_MouseUp(object sender,
System.Windows.Forms.MouseEventArgs e)
{
DataGrid.HitTestInfo hti;
hti=dbgEquipment.HitTest(e.X,e.Y);
if(e.Button == MouseButtons.Right)
{
if(hti.Type==DataGrid.HitTestType.RowHeader)
miHitRow = SelectCkBoxRow(ref thisdbgEquipment, e);
}
}

private int SelectCkBoxRow(ref DataGrid dbg,
System.Windows.Forms.MouseEventArgs e)
{
Point pt = new Point(e.X,e.Y);
DataGrid.HitTestInfo hti = dbg.HitTest(pt);
dbg.Select(hti.Row);
return(hti.Row);
}

No comments: