Assigning Value to StringValue In F#

128 views Asked by At

I am working though this example of the Open XML SDK using F#

When I get to this line of code

sheet.Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart)

I am getting a null ref exception when I implement it like this:

sheet.Id.Value <- document.WorkbookPart.GetIdOfPart(worksheetPart)

Is there another way to assign that value? System.Reflection?

2

There are 2 answers

0
Grzegorz SÅ‚awecki On BEST ANSWER

I got it working like this:

let sheet = new Sheet
                (
                    Id = new StringValue(spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart)), 
                    SheetId = UInt32Value.FromUInt32(1u), 
                    Name = new StringValue("mySheet")
                )

If You want to take a look to the entire sample translated to F#, it's here.

0
Tomas Petricek On

To clarify what's going on, the problem is that sheet.Id is initially null. If we look at the following:

sheet.Id.Value <- document.WorkbookPart.GetIdOfPart(worksheetPart)

The code tries to access the sheet.Id and invoke its Value property setter, but the Id itself is null. The answer posted by Grzegorz sets the value of the whole Id property - it's done in a construtor syntax, but it's equivalent to writing the following:

sheet.Id <- new StringValue(spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart))

This sets the whole Id property to a new StringValue instance.