Pregunta

In my Word addin I have a list of Range copy from Document.Words collection like below:

private void button1_Click(object sender, RibbonControlEventArgs e)
{
    Document doc = Globals.ThisAddIn.Application.ActiveDocument;
    List<Range> list = new List<Range>();
    foreach (Range word in doc.Words)
    { 
        list.Add(word);
    }
    MessageBox.Show("list: " + list[0].Text + "|"+ list[1].Text + "|"+ list[2].Text + "|"+      list[3].Text + "|"+ list[4].Text);

    list[0].Text = "Hello ";
    MessageBox.Show("list: " + list[0].Text + "|"+ list[1].Text + "|"+ list[2].Text + "|"+ list[3].Text + "|"+ list[4].Text);
}

Now I create a document containing "good good good.". After assign first item in list to "hello", the second item change too. The message show a list with "Hello ", "hello good " (???), "good". So what's wrong with my code?

¿Fue útil?

Solución

Try to add to the list not a reference to Range but its value (text):

var list = new List<string>();
foreach (Range range in doc.Words)
{ 
    list.Add(range.Text);
}

or shortly:

var list = new List<string>(doc.Words.Cast<Range>().Select(r => r.Text));

So now you can manipulate strings without referencing VSTO objects.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top