How can I programmatically delete a string from a Word document using C #?

I have code for finding and replacing fields in a Word document with values ​​from a dataset.

Word.Document oWordDoc = new Word.Document(); foreach (Word.Field mergeField in oWordDoc.Fields) { mergeField.Select(); oWord.Selection.TypeText( stringValueFromDataSet ); } 

In some cases, stringValueFromDataSet empty, and in addition to pasting nothing, I want to actually delete the current row.

Any idea how I can do this?

+4
source share
2 answers

Obviously your answer works in your case. However, in the general case (where the whole line cannot be deleted using backspace), you can use the following:

  private static object missing = System.Reflection.Missing.Value; /// <summary> /// Deletes the line in which there is a selection. /// </summary> /// <param name="application">Instance of Application object.</param> private void DeleteCurrentSelectionLine(_Application application) { object wdLine = WdUnits.wdLine; object wdCharacter = WdUnits.wdCharacter; object wdExtend = WdMovementType.wdExtend; object count = 1; Selection selection = application.Selection; selection.HomeKey(ref wdLine, ref missing); selection.MoveDown(ref wdLine, ref count, ref wdExtend); selection.Delete(ref wdCharacter, ref missing); } 
+4
source

OK it was funny easy at the end.

oWord.Selection.TypeBackspace();//remove the field
oWord.Selection.TypeBackspace();//remove the line

+5
source

All Articles