Invalid Cast Errors

A

Alan

I keep getting an invalid cast error on this line of code:

Dim gridCol As MyGridColumn = CType(dgt.GridColumnStyles(hi.Column),
MyGridColumn)

I am trying to develop a sub that will change the colors on a cell that
is clicked on in a DataGrid control.

Here is the full code:

Private Sub PaintCell(ByVal sender As Object, ByVal e As
MouseEventArgs)

Try
Dim hi As DataGrid.HitTestInfo
Dim grid As DataGrid = CType(sender, DataGrid)
hi = grid.HitTest(e.X, e.Y)
If hi.Type = DataGrid.HitTestType.Cell Then
Dim dgt As DataGridTableStyle =
dgvBranches.TableStyles(0)
Dim cm As CurrencyManager =
CType(Me.BindingContext(myDataSet.Tables(0)), CurrencyManager)
Dim cellRect As Rectangle
cellRect = grid.GetCellBounds(hi.Row, hi.Column)
Dim gridCol As MyGridColumn =
CType(dgt.GridColumnStyles(hi.Column), MyGridColumn)
Dim g As Graphics = dgvBranches.CreateGraphics()
Dim fBrush As New SolidBrush(Color.Blue)
Dim bBrush As New SolidBrush(Color.Yellow)
gridCol.PaintCol(g, cellRect, cm, hi.Row, bBrush,
fBrush, False)
End If
Catch ex As Exception
LogErrors(ex, "PaintCell")
End Try
End Sub 'PaintCell


Any help would be appreciated. Thanks!
 
C

Chris Dunaway

What data type is MyGridColumn? Does it inherit from another class?
Is the class it inherits from a DataGridColumnStyle? The
dgt.GridColumnStyles collection is a collection of DataGridColumnStyle
so if your gridCol is not a DataGridColumnStyle or a class that
inherits from it, the cast wont work.

Also, I noticed that your sub create a number of objects that need to
be disposed, namely the Graphics object and the Brush objects. You
should call .Dispose on these objects to free up their unmanaged
resources.
 
A

Alan

Sorry I knew there was something I forgot to add to this:

Public Class MyGridColumn
Inherits DataGridTextBoxColumn
Public Sub PaintCol(ByVal g As Graphics, ByVal cellRect As
Rectangle, _
ByVal cm As CurrencyManager, ByVal rowNum As Integer, ByVal bBrush
As Brush, _
ByVal fBrush As Brush, ByVal isVisible As Boolean)
Me.Paint(g, cellRect, cm, rowNum, bBrush, fBrush, isVisible)
End Sub
End Class

Perhaps that will answer your questions Chris.
 
C

Chris Dunaway

Are the items in dgt.GridColumnStyles in fact instances of
MyGridColumn? Can you verify using the debugger what type
dgt.GridColumnStyles(hi.Column) is? If it is a MyGridColumn instance
then I don't know why the cast is not working.

If if is an instance of one of the base classes (DataGridTextBoxColumn
or DataGridColumnStyle) then the cast won't work because you can't cast
from a base type to a derived type unless the object is, in fact, an
instance of the derived type.

PS. I still stand by recommendation to Dispose your brushes and
Graphics instances.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top