none
Drag and Drop mail Merge Fields from VSTO Plug IN ? RRS feed

  • Question

  • I have a VSTO plug-in I am bulding for Word. The Plug-in has a listbox control in which the user will click and drag selected items to the active word document. However, instead of just copying the selected text value of the listbox , I need it to create an appropriate mailmerge field. I spent some time researching and here(http://www.hightechtalks.com/dotnet-framework-interop/re-drag-drop-into-ms-183329.html) it more or less says I need the rtf representation of the mergefield. Upon trying to do the drag and drop currently I get the selectedtext plus an underscore after it inserted into my word doc. (So if the selected text is for example "Bob" then "Bob_" is inserted into my document when I do the drag and drop.) Then upon saving the document and performing a mailmerge against a datasource(and the datasource is not the problem) the mail merge does not work.

    So the question is how do I drag and drop mailmergefields? My code for my mousedown event is below. Any and all help will be greatly appreciated.

    Jason

        private void listBox1_MouseDown(object sender, MouseEventArgs e)
        {
          
           DataObject obj = new DataObject(DataFormats.Rtf, listBox1.SelectedItem.ToString());
          listBox1.DoDragDrop(obj, DragDropEffects.Copy);
    
         
          
    
        }
    

     


    Jason
    Tuesday, March 22, 2011 8:01 PM

Answers

  • If you are setting the data source on the document, you have direct access to mail merge fields through word. So let's say in my Data Source I have a column called PersonFirstName that is the 2nd column of my data source. You could programmatically insert a merge field as follows:

     

    int SelectedItemIndex = 2
    Word.MailMergeDataField mmdf = Globals.ThisDocument.MailMerge.DataSource.DataFields.get_Item(ref SelectedItemIndex);
    wordSelection = Globals.ThisDocument.ThisApplication.Selection;
    Globals.ThisDocument.MailMerge.Fields.Add(wordSelection.Range, mmdf.Name.ToString());
    

    So for what you're trying to do, if you can set the List Box items to match the order of your data source, or set a key value on your items so you know what merge field index to hit when they drag and drop from your list box, you'll get the desired result.

    Hopefully this makes sense.


    -dhtroy
    Wednesday, March 23, 2011 6:17 PM