Windows Forms Datagrid in .NET
doesn’t expose a property called MarqueeStyle which enabled VB6.0 users to
easily set the highlighting on a datagrid when the user clicks on a row. The
datagrid in is in edit mode by default. So when a user clicks on a row, it
highlights a cell instead of the row. Even if we set the ReadOnly property to
True, only the cell is highlighted. On initial examination there seems to be no
easy way of highlighting a row. But we can get the desired result by
manipulating the MouseUp event of the Datagrid.
To Highlight a row in Datagrid
1. Start a new windows project in VB.NET/C#
2. Drag and Drop a datagrid onto the default Form1
3. Accept the default name DataGrid1
4. Open the Code Editor for Form1
5. Expand the node “Windows Form Designer generated code”
6. After the “’Add any initialization after the InitializeComponent ()
call” comment add the following code
[VB.NET
Code]
AddHandler
DataGrid1.MouseUp, AddressOf highLightRow
[C# Code]
this.dataGrid1.MouseUp
+=new MouseEventHandler(highLightRow);
7. In the body of the form add the
following code
[VB.NET
Code]
Private
Sub highLightRow (ByVal sender As Object, ByVal e As MouseEventArgs)
Dim pt = New Point(e.X, e.Y)
Dim grd As DataGrid = CType (sender,
DataGrid)
Dim hit As DataGrid.HitTestInfo = grd.HitTest
(pt)
If hit.Type =
DataGrid.HitTestType.Cell Then
grd.CurrentCell = New DataGridCell
(hit.Row, hit.Column)
grd.Select (hit.Row)
End If
End
Sub
[C#
Code]
private
void highLightRow (object sender, MouseEventArgs e)
{
Point pt =new Point (e.X, e.Y);
DataGrid grd =sender as DataGrid;
DataGrid.HitTestInfo hitInfo=grd.HitTest (pt);
if (hitInfo.Type
==DataGrid.HitTestType.Cell)
{
grd.CurrentCell =new DataGridCell (hitInfo.Row,
hitInfo.Column);
grd.Select
(hitInfo.Row);
}
}
[VB.NET
code]
Private
Sub highLightRow (ByVal sender As Object, ByVal e AsMouseEventArgs)
Dim pt = New Point (e.X, e.Y)
Dim grd As DataGrid = CType (sender,
DataGrid)
Dim hit As DataGrid.HitTestInfo = grd.HitTest
(pt)
If hit.Type = DataGrid.HitTestType.Cell
Then
grd.CurrentCell = New DataGridCell
(hit.Row, hit.Column)
grd.Select (hit.Row)
End If
End
Sub
[C# Code]
private
void highLightRow (object sender, MouseEventArgs e){
Point pt =new Point (e.X, e.Y);
DataGrid grd =sender as DataGrid;
DataGrid.HitTestInfo
hitInfo=grd.HitTest(pt);
if (hitInfo.Type
==DataGrid.HitTestType.Cell)
{
grd.CurrentCell =new DataGridCell
(hitInfo.Row, hitInfo.Column);
grd.Select (hitInfo.Row);
}
}