且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将属性添加到块:Autocad API VB.net

更新时间:2023-12-06 16:54:04

我相信主要的问题是BlockReference的位置,并且您没有保存文件。我对代码进行了一些调整,但无法完全测试它,请检查下面的注释。

I believe the main problem are the BlockReference location and that you did not save the file. I made some adjusts on the code, but could not fully test it, check the comments below.

Public Sub addnewattribute() ' don't you mean define as Sub?
  Dim templatepath As String = "C:\Users\sesa388372\Documents\Visual Studio 2015\Projects\SchneiderMacros\Wtemplate.DWG"
  ' you must dispose this side database, the 'using' will take care of it
  Using db As Database = New Database(False, True) ' specify the parameters
    db.ReadDwgFile(templatepath, System.IO.FileShare.ReadWrite, False, "")
    db.CloseInput() ' this should help the Save() method
    Using tr As Transaction = db.TransactionManager.StartTransaction
      Dim bt As BlockTable = tr.GetObject(db.BlockTableId, OpenMode.ForWrite)
      Dim btr As BlockTableRecord = tr.GetObject(bt(BlockTableRecord.PaperSpace), OpenMode.ForWrite)
      For Each objid As ObjectId In btr
        If objid.ObjectClass.Name = "AcDbBlockReference" Then
          Dim blkref As BlockReference = tr.GetObject(objid, OpenMode.ForWrite)
          If blkref.Name = "TB-D-ATTR" Then
            ' define this variable inside the loop, you cannot reuse it
            Dim attdef As New AttributeReference
            attdef.SetDatabaseDefaults(db)
            attdef.Tag = "Cell location"
            attdef.TextString = "AAA"
            attdef.SetAttributeFromBlock(blkref.BlockTransform) ' adjust the location
            blkref.AttributeCollection.AppendAttribute(attdef)
            tr.AddNewlyCreatedDBObject(attdef, True)
          End If
        End If
      Next
      tr.Commit()
    End Using
    'Return Nothing ' in this case, a Sub (instead function) should be better
    db.Save() ' did you miss to save changes?
  End Using
End Sub