Foreach循环每个项目填充文档

时间:2014-01-13 10:32:37

标签: c#-4.0 itextsharp

我有一个列表,我想查看每个项目条件并将其插入到文档中。问题是我不知道如何找到一个项目并完成每个条件,直到项目发生变化然后重新开始。

Item    Condition       Total
Bag        New            3
Bag        Old            5
Jacket     New            2
Racket     New            1
Racket     old            3
Racket     unknown        8

这就是我的所作所为:

foreach (DataGridViewRow row in tracker.dataGridView1.Rows)
        {
            if (row.Cells[0].Value != null)
            {

                string template = @"C:\ document.pdf";
             string newFile = @"c:\"+ row.Cells[0].Value.ToString() +".pdf";
                PdfReader pdfReader = new PdfReader(pdfTemplate);
                PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create));
                AcroFields pdfFormFields = pdfStamper.AcroFields;

******************************************************************************

 // set values for fields
                        if (row.Cells[1].Value.ToString() == "New")
                        {
                            pdfFormFields.SetField("Condition", row.Cells[2].Value.ToString());
                        }
                        else if (row.Cells[1].Value.ToString() == "Old")
                        {
                            pdfFormFields.SetField("Condition2", row.Cells[2].Value.ToString());
                        }

***************************************************************************************              

                pdfStamper.FormFlattening = true;
                pdfStamper.Close();


            }
            else

            break;
        }

我希望星星之间的代码填充相同的文档,直到row.cells [0] .value更改然后再次启动foreach。

1 个答案:

答案 0 :(得分:0)

只需将row.cells [0] .value的值存储在变量中,并在foreach循环的每次迭代中进行比较。

您还必须将第一行与其余行区分开来,因为只有这样才能比较两个值。

示例代码:

string previousValue = null;
string currentValue = null;
bool firstRow = true;

foreach (DataGridViewRow row in tracker.dataGridView1.Rows)
{
    currentValue = row.Cells[0].Value.ToString();

    if (currentValue != null)
    {
            string template = @"C:\ document.pdf";
            string newFile = @"c:\"+ currentValue  +".pdf";
            PdfReader pdfReader = new PdfReader(pdfTemplate);
            PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create));
            AcroFields pdfFormFields = pdfStamper.AcroFields;


            // Compare previous with current value
            if (!firstRow && previousValue != currentValue)
            {
                // Difference, start new document
                ....

            }
            else
            {
                // Same Value
            }

            // When row is handled, update previous with current value, and set firstRow to false

            previousValue = currentValue;
            firstRow = false;
...