Error: System.ArgumentException: Style with that name already exists in the collection.

Hi there,

I’m currently experimenting with the trial version of GemBox and we are intending to use it in our application. I’m trying to create a custom style to apply to my table but I keep getting the following error:

Error: System.ArgumentException: Style with that name already exists in the collection.

I haven’t created any other styles in my code so I’m not sure why it thinks my style already exists.

Here is the relevant part of my code:

foreach (var link in formDto.FormAspectGradeLinks)
{
    var aspect = await repo.GetAspect(link.AspectId);

    var llAspectTableStyle = new TableStyle("LLAspectsTable");
    document.Styles.Add(llAspectTableStyle);

    var firstRowFormat = llAspectTableStyle.ConditionalFormats[TableStyleFormatType.FirstRow];
    firstRowFormat.CharacterFormat.Bold = true;
    firstRowFormat.CharacterFormat.FontColor = Color.White;

    var firstColumnFormat = llAspectTableStyle.ConditionalFormats[TableStyleFormatType.FirstColumn];
    firstColumnFormat.CharacterFormat.Bold = true;

    var aspectTable = new Table(document,
        new TableRow(document,
            new TableCell(document, new Paragraph(document, aspect.Name))
            {
                ColumnSpan = 2
            }),
        new TableRow(document,
            new TableCell(document, new Paragraph(document, "Comments")),
            new TableCell(document, new Paragraph(document, link.Comments != null ? link.Comments : ""))),
        new TableRow(document,
            new TableCell(document, new Paragraph(document, "Grade")),
            new TableCell(document, new Paragraph(document, "Grade goes here."))));

    aspectTable.TableFormat.Style = llAspectTableStyle;
    aspectTable.TableFormat.StyleOptions = TableStyleOptions.FirstRow | TableStyleOptions.FirstColumn;
}

Is anybody able to assist?

Hi!

Are you editing an existing Word file? If you are, then that file already contains a style with that name. Try changing the name of the style to something line ‘LLAspectsTable1’.

Hi Marko,

Yes, I am using an existing Word file. Further up in my code I use:

using var inputStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("LessonsLearnedWebApp.Resources.LessonsLearnedQAFormTemplate.docx")!;
var document = DocumentModel.Load(inputStream, LoadOptions.DocxDefault);

I’ve tried changing the name to LLAspectsTable1 as you suggested but I’m still getting the error, which is strange because I doubt there is a style called LLAspectsTable1…

My full code is very long but I’ve included it below in case there’s something I’m missing.

async Task PrintForm()
{
    ComponentInfo.SetLicense("FREE-LIMITED-KEY");

    // Continue to use the component in a Trial mode when free limit is reached.
    ComponentInfo.FreeLimitReached += (sender, e) => e.FreeLimitReachedAction = FreeLimitReachedAction.ContinueAsTrial;

    // Load template document.
    using var inputStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("LessonsLearnedWebApp.Resources.LessonsLearnedQAFormTemplate.docx")!;
    var document = DocumentModel.Load(inputStream, LoadOptions.DocxDefault);

    document.Content.Replace("{{SchoolName}}", schoolSettings.SchoolName != null ? schoolSettings.SchoolName : "");
    document.Content.Replace("{{PrintDate}}", DateTime.Now.ToLongDateString());

    document.Content.Replace("{{FormType}}", formDto.FormType.Name);
    document.Content.Replace("{{Date}}", formDto.FormDate.ToShortDateString());
    document.Content.Replace("{{FormOn}}", formDto.UserOn != null ? formDto.UserOn.FullName! : "N/A");
    document.Content.Replace("{{Series}}", formDto.Series != null && formDto.Series.Name != null ? formDto.Series.Name : "N/A");
    document.Content.Replace("{{FormCreator}}", formDto.UserBy != null ? formDto.UserBy.FullName! : "N/A");
    document.Content.Replace("{{IsDraft}}", formDto.IsDraft == true ? "Yes" : "No");

    var section = document.Sections[0];

    using (var repo = new QualityAssuranceService(_contextFactory!.CreateDbContext(), _memoryCache!))
    {
        // Aspects

        if (formDto.FormAspectGradeLinks.Count() > 0)
        {
            foreach (var link in formDto.FormAspectGradeLinks)
            {
                var aspectData = await repo.GetFormAspectData(formDto.Id, link.AspectId, userSettings.UserId);

                var llAspectTableStyle1 = new TableStyle("LLAspectsTable1");
                document.Styles.Add(llAspectTableStyle1);

                var firstRowFormat = llAspectTableStyle1.ConditionalFormats[TableStyleFormatType.FirstRow];
                firstRowFormat.CharacterFormat.Bold = true;
                firstRowFormat.CharacterFormat.FontColor = Color.White;

                var firstColumnFormat = llAspectTableStyle1.ConditionalFormats[TableStyleFormatType.FirstColumn];
                firstColumnFormat.CharacterFormat.Bold = true;

                var aspectTable = new Table(document,
                    new TableRow(document,
                        new TableCell(document, new Paragraph(document, aspectData.FormAspectGradeLink.Aspect.Name))
                        {
                            ColumnSpan = 2
                        }),
                    new TableRow(document,
                        new TableCell(document, new Paragraph(document, "Comments")),
                        new TableCell(document, new Paragraph(document, link.Comments != null ? link.Comments : ""))),
                    new TableRow(document,
                        new TableCell(document, new Paragraph(document, "Grade")),
                        new TableCell(document, new Paragraph(document, "Grade goes here."))));

                aspectTable.TableFormat.Style = llAspectTableStyle1;
                aspectTable.TableFormat.StyleOptions = TableStyleOptions.FirstRow | TableStyleOptions.FirstColumn;

                aspectTable.TableFormat.PreferredWidth = new TableWidth(100, TableWidthUnit.Percentage);
                aspectTable.TableFormat.DefaultCellPadding = new Padding(5);
                aspectTable.TableFormat.Style.TableFormat.Borders.ClearBorders();

                int decValue = int.Parse(schoolSettings.ColourHex.Replace("#", ""), System.Globalization.NumberStyles.HexNumber);

                aspectTable.Rows[0].Cells[0].CellFormat.BackgroundColor = new Color(decValue);
                aspectTable.Rows[1].Cells[0].CellFormat.PreferredWidth = new TableWidth(20, TableWidthUnit.Percentage);

                section.Blocks.Add(aspectTable);
                section.Blocks.Add(new Paragraph(document));
            }

        }
    }

    // Save document in specified file format.
    var outputStream = new MemoryStream();
    document.Save(outputStream, new DocxSaveOptions());

    // Download file.
    using var streamRef = new DotNetStreamReference(outputStream);
    await JS.InvokeVoidAsync("downloadFileFromStream", $"BlazorWebAssemblyOutput.docx", streamRef);

    _dialogService.Close();
}

Can you share the DOCX file?

Hi,

The problem occurs because you’re creating the same “LLAspectsTable” style inside the foreach loop.
Try using this instead:

var llAspectTableStyle = new TableStyle("LLAspectsTable");
document.Styles.Add(llAspectTableStyle);

foreach (var link in formDto.FormAspectGradeLinks)
{
    // ...
    aspectTable.TableFormat.Style = llAspectTableStyle;
    aspectTable.TableFormat.StyleOptions = TableStyleOptions.FirstRow | TableStyleOptions.FirstColumn;
}

Does this solve your issue?

Regards,
Mario