2

I have a program that loads a shapefile into memory, groups some of the features based on business logic, creates a shapefile out of each group of features, and then saves the files to a cloud location for use in other applications.

The one sticking point in this process has been the attribute table. I had wanted to be able to set custom attributes for the features in the new shapefiles. With the code below I am able to update the datatable with the desired information, but I can't make it persist once I save and dispose the shapefile object.

var table = shapefile.DataTable;
var i = 0;

foreach(var branchObject in branches)
{
    shapefile.AddFeature(branchObject.Feature);

    var row = table.Rows[i];
    row.BeginEdit();
    row["BranchName"] = branchObject.Name;
    row.EndEdit();
    i++;
}

table.AcceptChanges();

This gives me a properly-populated DataTable in the shapefile, but when I open the shapefile in MapWindow5, the only field in the attribute table is the auto-generated Id.

I'm clearly missing some sort of "Save Changes" step that I thought was encompassed in "AcceptChanges()" or "Being/EndEdit()"...what else needs to be called on the table to make it update?

I have a feeling this was covered in one of the tutorials that I can't find since Codeplex sunsetted, but as it is Google hasn't been very helpful.

jdmac020
  • 557
  • 1
  • 5
  • 18

1 Answers1

2

As it turns out, my DataTable and DataRows were fine. One has to explicitly tell the shapefile to update it's attribute table after changes are made.

shapefile.Filename = $"{filePathWithName}.shp";
shapefile.UpdateAttributes();

These two lines of code just before saving the shapefile, and I can now see the attribute table of my dreams in MapWindow5.

Note:

Calling

shapefile.UpdateAttributes();

without first setting the shapefile.Filename property will throw an exception.

Updating the attributes evidently requires saving to the .dbf file of the shapefile package, and it can't do that without knowing where that .dbf file is supposed to go. This called for some refactoring for me as the output shapefile didn't exist outside memory till the end of the process.

jdmac020
  • 557
  • 1
  • 5
  • 18