How to check for Empty when extracting SdtBlock
-
Thursday, February 16, 2012 12:55 PM
I have the following code which works perfect if the document contains the content control which has tag name same as the variable value.
mainPart.Document.Body.Descendants<sdtblock>().Where(r => r.SdtProperties.GetFirstChild<tag>().Val == myVar).Single();</tag></sdtblock>
But this line throws a Sequence is Empty exception if the document does not contain any content control which has the Tag/Title of the variable value.
Can you please tell me how to build some resiliency in the code?
MSDNStudent Knows not much!
- Edited by MSDN Student Thursday, February 16, 2012 8:27 PM
All Replies
-
Friday, February 17, 2012 5:48 AMModerator
Hi,
You can use Try Catch statement to prevent getting a exception if the document doesn't contain any Content Controls or there is a content control whose tag name matches what you specify, see:
SdtBlock block = null; try { block = body.Descendants<SdtBlock>().Where(r => r.SdtProperties.GetFirstChild<Tag>().Val == var).First(); } catch { } if (block != null) { block.SdtProperties.GetFirstChild<Tag>().Val = "MyCustomTag"; }
i hope this helps.
Calvin Gao[MSFT]
MSDN Community Support | Feedback to us
- Marked As Answer by Calvin_GaoModerator Monday, February 20, 2012 3:19 AM
-
Friday, February 17, 2012 11:18 AM
I am currently using FirstOrDefault method. this is causing the error to stopMSDNStudent Knows not much!
- Marked As Answer by Calvin_GaoModerator Monday, February 20, 2012 3:19 AM

