views:

338

answers:

1

Discussion on OOoForum.org

In python, using pyuno, I can do it like this:

table = self.model.createInstance("com.sun.star.text.TextTable")

This doesn't seem to work in C#. Here is my test code (I realize I probably don't need all those using statements, but I am adapting someone else's code):

using System;
using unoidl.com.sun.star.lang;
using unoidl.com.sun.star.uno;
using unoidl.com.sun.star.bridge;
using unoidl.com.sun.star.frame;
using unoidl.com.sun.star.document;
using unoidl.com.sun.star.text;
using unoidl.com.sun.star.container;
using unoidl.com.sun.star.util;
using unoidl.com.sun.star.table;
using unoidl.com.sun.star.beans;

namespace FromScratch
{
    class MainClass
    {
     public static void Main(string[] args)
     {
      XComponentContext componentContext =
       uno.util.Bootstrap.bootstrap();
      XMultiServiceFactory multiServiceFactory = (XMultiServiceFactory)
       componentContext.getServiceManager();
      XTextDocument document;
      XComponentLoader loader = (XComponentLoader)
       multiServiceFactory.createInstance
        ("com.sun.star.frame.Desktop");
      document = (XTextDocument) loader.loadComponentFromURL
       ("private:factory/swriter", "_blank", 0,
        new PropertyValue[0]);

      XText text = document.getText();
      XTextCursor cursor = text.createTextCursor();

      XTextTable table = (XTextTable)
       multiServiceFactory.createInstance
        ("com.sun.star.text.TextTable");
      table.initialize(2, 2);
      text.insertTextContent(cursor, table, false);

     }
    }
}

Most of it seems to work fine, but when it gets to this line:

table.initialize(2, 2);

I get a runtime error:

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object
  at FromScratch.MainClass.Main (System.String[] args) [0x00063] in /home/matthew/Desktop/OpenOfficeSample/FromScratch/Main.cs:37

Apparently, this line:

XTextTable table = (XTextTable)
    multiServiceFactory.createInstance
    ("com.sun.star.text.TextTable");

doesn't actually set table to anything.

What is going on here?

A: 

Solution (from OOoForum.org):

You must get the text table from the document multiservice factory, not from the multiservice factory of the service manager. You can do this by casting your document (a Model) to XMultiServiceFactory and calling its createInstance method.

XTextTable table = (XTextTable) 
    ((XMultiServiceFactory)document).createInstance 
    ("com.sun.star.text.TextTable");

See DevGuide.

Matthew