Hello All, When I use the code as posted I get the attributes repeated for every instance of the block. I only want them once. I tried changing the way I retrieve the instance to btr by indexing into the blockTable as such; bt[blockName], however that approach never gets me an AcDbBlockReference. I have years of c# under my belt, but I'm new to AutoCAD.NET. Thanks in advance.
try
{
string BName = lstBlockName.SelectedItem.ToString();
BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
//using the following with a foreach repeats the attributes for each instance of the block
// BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead);
BlockTableRecord btr = GetBtr(tr, BName, bt);
foreach (ObjectId bId in btr)
{
using (Entity ent = (Entity)tr.GetObject(bId, OpenMode.ForRead, false))
{
if (ent.GetRXClass().Name.ToString() == "AcDbBlockReference")
{
BlockReference br = (BlockReference)ent;
BlockTableRecord blkObj = (BlockTableRecord)tr.GetObject(br.BlockTableRecord, OpenMode.ForRead);
if ((blkObj.HasAttributeDefinitions) && (blkObj.Name == BName))
{
For anyone looking at this in the future, searching for answers: this was inordinately helpful
http://adndevblog.typepad.com/autocad/2012/06/identify-the-number-of-reference-to-a-block.html
just incase the link gets broken in a few years, here is the money, the code below. What a Godsend it is!
[CommandMethod("BlockRefCount")]
static public void BlockRefCount()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
PromptStringOptions opts =
new PromptStringOptions("Enter block name");
opts.AllowSpaces = true;
PromptResult blockName = ed.GetString(opts);
if (blockName.Status != PromptStatus.OK)
return;
using (Transaction tx =
db.TransactionManager.StartTransaction())
{
BlockTable blockTable = tx.GetObject(db.BlockTableId,
OpenMode.ForRead) as BlockTable;
if (blockTable.Has(blockName.StringResult))
{
BlockTableRecord block = tx.GetObject(
blockTable[blockName.StringResult],
OpenMode.ForRead) as BlockTableRecord;
//only direct reference
ObjectIdCollection ids =
block.GetBlockReferenceIds(true, true);
ed.WriteMessage("Number of reference is "
+ ids.Count.ToString() + "\n");
}
tx.Commit();
}
}