Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Datagridview - current row and cell becomes -1 and throws exception

Status
Not open for further replies.

Yorkshireman2

Programmer
Jan 21, 2005
154
CA
My datagridview is bound to a datatable.
As the form loads a filter is applied to the datatable and the datagridview_CurrentCellChanged event fires.
In this event, an exception (System.NullReferenceException "Object reference not set to an instance of an object.") is thrown.

To debug, I first print to immediate window the CurrentCellAddress and this prints out {X=-1,Y=-1} which does not see mright, so I am pretty sure the exception is because the current cell address becomes -1,-1 for some reason.
I tried putting in a simple statement ahead of the datatable access statement that caused this, to see if I could at least read the rowindex
Code:
Dim i As Integer = dgv1.CurrentRow.Index

Even this throws the exception so it must be the row and cell index rather than the datatable fields.
- has anyone come across this one?? Why did row,col become -1, -1


 

In Declarations put this:

Dim bLoading as boolean = False

in Form_Load, put this first:

bLoading = True

and at the end of Form_Load, put this:

bLoading = False


Then, first line in the datagridview_CurrentCellChanged event:

If bLoading Then Return

This should take care of the problem.

I used to rock and roll every night and party every day. Then it was every other day. Now I'm lucky if I can find 30 minutes a week in which to get funky. - Homer Simpson

Arrrr, mateys! Ye needs ta be preparin' yerselves fer Talk Like a Pirate Day!
 
Yes- I already do that but... after loading the form, every time I change filter on the datatable the cells in the grid change and it happens again.
If you think the -1 values are occurring while the grid is refreshing/loading then maybe every time I apply a fliter I can try setting the flag again and clearing after finished.

I'll let you know.

(ps this never happened with vb6 datagrid and recordset- the same program has been working smoothly for some years in vb6.
so far it seems MS made everything worse with .net)
 
Well, so far it seems to have fixed it. I haven't tried every operation yet but I did comment out the flags in my filter routine and after a few attempts I got the exception again; uncommented the flags and all goes well.
Thanks jebenson, it seems MS wrote the event sequences in the datagridview so differently compared to the vb6 datagrid that filtering can produce invalid current cell addresses (-1,-1).
I hope that will be the end of the problem.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top