Friday, 15 February 2019

arcobjects - vb.net arcmap add-in loop through a dbf file get 'System.NullReferenceException' error


I am using vb.net arcmap add-in.


I encounter a System.NullReferenceException error and cause arcmap crash. The workflow in my vb.net code is:


(1) create a ShapefileWorkspaceFactory


(2) use the workspace to open a DBF file as ITable



(3) loop through each record and get related value


The code I am using:


    Dim pWSF As ShapefileWorkspaceFactory = New ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactory()
Dim pWS As ESRI.ArcGIS.Geodatabase.IWorkspace = pWSF.OpenFromFile("D:/dev/local", 0)
Dim pFws As ESRI.ArcGIS.Geodatabase.IFeatureWorkspace = CType(pWS, ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)
Dim pTable As ESRI.ArcGIS.Geodatabase.ITable = pFws.OpenTable("Segment_line_intersect")
Dim pCur As ESRI.ArcGIS.Geodatabase.ICursor = pTable.Search(Nothing, False)
Dim queryFilter As IQueryFilter = New QueryFilterClass()
Dim pFieldIndex1 As Integer = pTable.Fields.FindField("Segment_ID")
Dim pFieldIndex2 As Integer = pTable.Fields.FindField("DrainName")


Dim pRow As ESRI.ArcGIS.Geodatabase.IRow = pCur.NextRow
Dim SegmentID As String
Dim DrainName As String

Do Until pRow Is Nothing
pRow = pCur.NextRow

SegmentID = pRow.Value(pFieldIndex1)
DrainName = pRow.Value(pFieldIndex2)


MsgBox("SegmentID = " + SegmentID)
MsgBox("DrainName = " + DrainName)

Loop

All the values of SegmentID and DrainName can be retrieved correctly, but once all the values retrieved, the map crash. I use debug mode to track the error and get 'System.NullReferenceException' error.


I believe there is something wrong with my code, but I cannot tell what cause the issue.


I am using arcmap 10.2.2.



Answer




This line:


pRow = pCur.NextRow

should be at the end of your loop


Do Until pRow Is Nothing

SegmentID = pRow.Value(pFieldIndex1)
DrainName = pRow.Value(pFieldIndex2)

MsgBox("SegmentID = " + SegmentID)

MsgBox("DrainName = " + DrainName)

pRow = pCur.NextRow

Loop

I think it's failing because you're trying to retrieve a value when pRow is null. Plus you were skipping the first record of your table because you called NextRow twice before starting your logic.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...