iText7 表格数组

问题描述 投票:0回答:1

代码片段将编译,但运行时会抛出 NullReferenceException。它说“对象未设置为对象的实例”。该代码是在 VS2019 上使用 .NET Core 3.1 创建的。 我找不到任何证据证明这段代码是否可以运行。 非常感谢您的帮助。

 class Program
    {        
        static PdfDocument pdfTable;
        static Document document;
        static string destination;
              
        static void Main()
        {            
            destination = Path.Combine(@"C:\Users\Administrator\Documents", "SRC_Selection.pdf");
            pdfTable = new PdfDocument(new PdfWriter(destination));
            document = new Document(pdfTable); 
            
            // some usual MySql-stuff here

            using (MySqlDataReader reader = cmd.ExecuteReader())
            {
                List<Table> tables = new List<Table>();
                for(i = 0; i < 10; i++) tables.Add(new Table(1, true)); 
                Cell[] cell = new Cell[reader.FieldCount];

                int i = 0;
                while (reader.Read())
                { 
                   For (int j = 0; j < reader.FieldCount-1; j++)        
                   {
                        cell[j] = new Cell(1, 1)   
                          .SetFontSize(10)
                          .SetTextAlignment(TextAlignment.LEFT)
                          .Add(new Paragraph(reader.GetString(j)));
                
                        tables[i].AddCell(cell[j]);  // exception thrown here!
                   }

                   document.Add(tables[i]).Add(newline);
                   i++;
                }
            }
        }
    }
c# arrays pdf nullreferenceexception itext7
1个回答
0
投票

您得到的 NullReferenceException 可能是由于您声明了一个 Table 对象数组 (

Table[] table = new Table[10];
),但尚未初始化该数组的每个元素。检查下面的代码。

for (int j = 0; j < reader.FieldCount; j++)
{
    table[i] = new Table(reader.FieldCount - 1); // Initialize the table with the appropriate number of columns

    cell[j] = new Cell(1, 1)
        .SetFontSize(10)
        .SetTextAlignment(TextAlignment.LEFT)
        .Add(new Paragraph(reader.GetString(j)));

    table[i].AddCell(cell[j]);
}
© www.soinside.com 2019 - 2024. All rights reserved.