What is the code that add field to layer and does an operation?

469
1
11-30-2010 02:48 PM
JamalNUMAN
Legendary Contributor
What is the code that add field to layer and does an operation

Please, see the attached image that shows my question

When I press the button in the form, I need to add field to the layer ???School??? and to divide the field maths on pupils

What is the code?

Thank you
----------------------------------------
Jamal Numan
Geomolg Geoportal for Spatial Information
Ramallah, West Bank, Palestine
0 Kudos
1 Reply
TomGiles
New Contributor
Hi Jamal,

I'm no expert, but I would think this could be done much easier in a python script tool; partly because I have the code in front of me... 🙂

I've removed all the try/excepts, but it would look something like this:

import arcpy

fc = arcpy.GetParameterAsText(0)                                   #this would come from a input box (the only one in the tool)

if len(arcpy.ListFields(fc, "aFieldName")) < 1:                      #check if your new field exists otherwise create it
     arcpy.AddField_management(fc, "aFieldName", "DOUBLE")     

rows=arcpy.UpdateCursor(fc)

for row in rows:
     row.aFieldName = row.Math / row.Pupil #whatever calculation you need to do

rows.updateRow(row)
del row
del rows





Now in vb... which I don't have the code for, it would look something like this:

'i dont show var declarations in the first init step here
'load map, layer, etc, my 'm_application' is passed to my form_init function, so I start with getting the map doc from this

pMxDoc = m_application.Document
pMap = pMxDoc.FocusMap
pLayer = pMxDoc.SelectedLayer


'once you have the FC loaded (pFC) you can access fields for selected records by:

Dim pFc = pLayer.FeatureClass
pFC = pLayer.FeatureClass
Dim pFSel As IFeatureSelection
pFSel = pLayer
Dim pSelSet As ISelectionSet
pSelSet = pFSel.SelectionSet
pSelSet.Search(Nothing, False, pFCur)



Now you have a pFCur which is a cursor of all selected features
You can access each by a for loop using pFeat = pFCur.NextFeature (declared as Dim pFeat As IFeatureCursor)
You change individual values by finding the index for a field like this:
Dim aNewFieldIndex As Integer
aNewFieldIndex = pFC.FindField("aNewField")
and change values by the index, like this:
pFeat.Value(aNewFieldIndex) = "1" (or a variable from a calculation from other fields)



Like I said I would use the python option, and you can throw it into a batch grid and drag FCs from ArcCatalogue, without even opening the data.





Cheers,
Tom
0 Kudos