Civil 3D uses a base class LabelBase to handle labels and the features that it’s being labeled. This is done using the FeatureId property, which is available for all labels. The following code show a generic approach for this.
[CommandMethod("testReadLabelFeature")]
public void CmdReadLabelFeature()
{
Database db = Application.DocumentManager.MdiActiveDocument.Database;
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
PromptEntityOptions peo = new PromptEntityOptions("\nSelect a label: ");
peo.SetRejectMessage("\nPlease select a Label, try again.");
peo.AddAllowedClass(typeof(LabelBase), true);
PromptEntityResult per = ed.GetEntity(peo);
if (per.Status != PromptStatus.OK) return;
using (Transaction tr = db.TransactionManager.StartTransaction())
{
// open the label
LabelBase genericLabel = tr.GetObject(per.ObjectId,
OpenMode.ForRead) as LabelBase;
// open the entity that this label points to
Autodesk.AutoCAD.DatabaseServices.Entity featureEnt = tr.GetObject(
genericLabel.FeatureId, OpenMode.ForRead)
as Autodesk.AutoCAD.DatabaseServices.Entity;
if (featureEnt != null)
{
// now we know this label points to an entity...
// is it the one we need?
if (featureEnt is Pipe)
{
// is a Pipe, can do something related to PipeLabel
PipeLabel pipeLabel = genericLabel as PipeLabel;
Pipe pipe = featureEnt as Pipe;
}
}
else
{
// make a test to ensure is valid
ed.WriteMessage("\nThis label is not linked to an entity. Sorry");
}
tr.Commit();
}
}