Cross post from: https://geonet.esri.com/thread/125010
Does anyone know how to change the data source of a table using arcobjects? I know it can be done with arcpy, but I'm using C#. I've managed to change the source of all the layers in the mxd, but I need to do tables too.
I've come up with a solution by adding and removing from the table collection.
Is this the best way to do it?
IMap map = ...;
IWorkspace = ...;
ITableCollection tableCollection = (ITableCollection)map;
int tableCount = tableCollection.TableCount;
// iterate over a copy of the tables so we can add and remove
List tables = new List();
for (int i = 0; i < tableCount; i++)
{
tables.Add(tableCollection.get_Table(i));
}
foreach (ITable oldTable in tables)
{
IDataset dataset = (IDataset)oldTable;
IDatasetName datasetName = (IDatasetName)dataset.FullName;
string workspaceName = datasetName.WorkspaceName.PathName;
// get the new table
ITable newTable = ((IFeatureWorkspace)workspace).OpenTable(datasetName.Name);
// replace the table in the TOC
tableCollection.RemoveTable(oldTable);
tableCollection.AddTable(newTable);
// fire change event to change table
IMapAdmin2 mapAdmin2 = (IMapAdmin2)map;
mapAdmin2.FireChangeTable(oldTable, newTable);
}
Note: this is simplified - I did check the table was in the new workspace before opening it.
Answer
You should use the table property of IStandaloneTable to change its datasource. First create a reference to the new ITable (e.g. a table from a geodatabase), then use this code to replace the Table property:
IMap map = ...;
IStandaloneTableCollection tbcol= (IStandaloneTableCollection)map;
for (int i = 0; i < tbcol.StandaloneTableCount; i++)
{
var stTable = tbcol.get_StandaloneTable(i);
stTable.Table = newTable; //Here put the new ITable To change the datasource
if (!stTable.Valid)
MessageBox.Show("Table is not valid, "+stTable.Name);
}
No comments:
Post a Comment