Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleFind the location of a cell in a DataGridView in Visual Basic 2005
DescriptionThis example shows how to find the location of a cell in a DataGridView in Visual Basic 2005.
Keywordscell location, cell position, DataGridView, Visual Basic 2005
CategoriesVB.NET, Controls
 
The DataGridView control's GetCellDisplayRectangle function returns a Rectangle indicating where a particular cell is relative to the control's upper left corner. The following code shows how the program finds cell (1, 1) and draws lines showing its location when the form resizes. (I've removed the event handler's parameters to make the code easier to read.)
 
Private Sub Form1_Paint(...) Handles Me.Paint
    ' Find cell (1, 2).
    Dim rect As Rectangle = _
        DataGridView1.GetCellDisplayRectangle(1, 1, False)
    Dim x1 As Integer = DataGridView1.Left
    Dim y1 As Integer = DataGridView1.Top
    Dim the_pen As Pen
    If DataGridView1.Rows(1).Cells(1).Displayed Then
        the_pen = Pens.Blue
    Else
        the_pen = Pens.Red
    End If
    e.Graphics.DrawLine(the_pen, 0, y1 + rect.Top, _
        Me.ClientSize.Width, y1 + rect.Top)
    e.Graphics.DrawLine(the_pen, 0, y1 + rect.Bottom, _
        Me.ClientSize.Width, y1 + rect.Bottom)
    e.Graphics.DrawLine(the_pen, x1 + rect.Left, 0, x1 + _
        rect.Left, Me.ClientSize.Height)
    e.Graphics.DrawLine(the_pen, x1 + rect.Right, 0, x1 + _
        rect.Right, Me.ClientSize.Height)
End Sub
 
Whenever the user resizes a row or column, or scrolls the DataGridView, the program invalidates itself so it gets a new Paint event and redraws to show cell (1, 1)'s new position.
 
Private Sub DataGridView1_ColumnWidthChanged(...) Handles _
    DataGridView1.ColumnWidthChanged
    Me.Invalidate()
End Sub
Private Sub DataGridView1_RowHeightChanged(...) Handles _
    DataGridView1.RowHeightChanged
    Me.Invalidate()
End Sub
Private Sub DataGridView1_Scroll(...) Handles _
    DataGridView1.Scroll
    Me.Invalidate()
End Sub
 
 
Copyright © 1997-2006 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated