c# – How to change the text of a table cell that is inside a Flowdocument that is in a RichTextBox

Question:

I'm trying the following code to replace the text in the question situation, where rtb is richtextbox , .Document is flowdocument . The text is exchanged in Run (r), but when I open the document the exchange was not made.

foreach (Block oBlock in rtb.Document.Blocks)
{
    Paragraph oParagraph = oBlock as Paragraph;
    if (oParagraph != null)
    {
        foreach (Inline il in oParagraph.Inlines)
        {
            if (il is Figure)
            {
                foreach (Block bl in ((System.Windows.Documents.AnchoredBlock)(il)).Blocks)
                {
                    if (bl is Table)
                    {
                        Table t = bl as Table;

                        foreach (Block cellBlock in t.RowGroups[reportReference.RowGroup].Rows[reportReference.Line].Cells[reportReference.Column].Blocks)
                        {
                            Paragraph p = cellBlock as Paragraph;
                            if (p != null)
                            {
                                Run r = p.Inlines.FirstInline as Run;
                                if (r != null && r.Text.Contains(searchEntry))
                                {
                                    r.ContentStart.DeleteTextInRun(searchEntry.Length + 1);
                                    r.ContentStart.InsertTextInRun(Constants.TagId + newName);;
                                }   
                            }
                        }

                    }
                }
            }
        }
    }
}

Any suggestions on how to do this?

Answer:

I found the code above difficult to understand, for a quick analysis, and transcribed it into a link. Replace the code above with:

var colecao = rtb.Document
                 .Blocks
                 .OfType<Paragraph>() //recupera os blocos do tipo Paragraph
                 .SelectMany(p=>p.Inlines.OfType<Inline>().Where(il=>il is Figure)) //Recupera os inline do tip Figure do Paragraph acima
                 .SelectMany(li=> ((System.Windows.Documents.AnchoredBlock)(il)).Blocks.OfType<Table>()) //Faz a conversão das figuras e recupera os blocos do tipo Table
                 .SelectMany(t=>t.RowGroups[reportReference.RowGroup].Rows[reportReference.Line].Cells[reportReference.Column].Blocks) //Recup os Blocks das celulas das linhas do grupo
                 .OfType<Paragraph>() //Recupera os do Tipo Paragraph
                 .Select(p=>p.Inlines.FirstInline as Run)
                 .Where(r=>r!=null&& r.Text.Contains(searchEntry))  //Executa o filtro para manter a colecao somente com os objetos necessarios
                 .ToArray();

foreach(var r in colecao){

     r.ContentStart.DeleteTextInRun(searchEntry.Length + 1);
     r.ContentStart.InsertTextInRun(Constants.TagId + newName);;
  }   

If it provides any improvement, post here

Scroll to Top