C#String Concatenation OutOfRange错误

时间:2015-04-25 16:52:06

标签: c# string-concatenation

我正在利用“Label”类中的Get String函数将行打印在一个位图上。程序编译正常,前一个表单正确传递LabelQueue(在我尝试打印位图之前,它看起来没有问题)。下面是这个特定初始化程序/构造函数的所有代码。错误的代码行是“c ++”之前函数的最后三行。

如果您需要我添加更多必要的代码,请告诉我。

我收到一个IndexOutofRange异常,声称它超出了数组的范围。

private LabelQueue lq;
    public Print(LabelQueue queue)
    {
        InitializeComponent();
        lq = queue;
        pictureBox1.Image = new Bitmap(2550, 3300);

        System.Drawing.Graphics formGraphics = this.CreateGraphics();
        System.Drawing.Font textFont = new System.Drawing.Font("Times New Roman", 8);
        System.Drawing.SolidBrush textBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);
        System.Drawing.StringFormat textFormat = new System.Drawing.StringFormat();

        int x, y, c = 0;

        while (c < 30)
        {
            // Get coordinates for where to put values.
            x = ((c % 3) * 600) + 300;
            // Accounts for column gap
            if (c % 3 > 0)
                x = x + ((c % 3) - 1) * 75;
            y = ((c % 10) * 270) + 300;

            string firstLine, secondLine, thirdLine;

            firstLine = lq.labels[c].GetLastName() + ", " + lq.labels[c].GetFirstName() + " " + lq.labels[c].GetMiddleName();
            secondLine = lq.labels[c].GetNewStreet();
            thirdLine = lq.labels[c].GetNewCity() + ", " + lq.labels[c].GetNewState() + lq.labels[c].GetNewZIP() + lq.labels[c].GetNewCountry();

            formGraphics.DrawString(firstLine, textFont, textBrush, x, y, textFormat);  // Line turning up the error
            formGraphics.DrawString(firstLine, textFont, textBrush, x, y + 10, textFormat);  // Naturally, both these lines would need to be fixed too
            formGraphics.DrawString(firstLine, textFont, textBrush, x, y + 20, textFormat);

            c++;
        }

    }

1 个答案:

答案 0 :(得分:0)

如果没有a good, minimal, complete code example可靠地证明问题,就无法确切知道您需要的确切修复。

但是,根据此问题的信息和到目前为止的评论,您似乎并没有正确限制循环。 while语句应如下所示:

while (c < lq.Count())

请注意,上面使用了Enumerable.Count()扩展方法。我选择了这个作为答案,因为你没有包含你的LabelQueue对象的声明/实现,所以没有办法确定正确的语法是什么,但扩展方法可能会起作用,因为几乎任何支持索引器的合理集合类型都会实现某些接口,允许Enumerable.Count()方法正常工作。

也就是说,您的类型可能具有Count属性,您可以使用该属性代替Count()扩展方法。两者都可以同样有效。


最后,为了将来参考,可以回答您自己的问题。这只是你的答案应该成为一个答案。即它需要清楚地解释什么是错的,以及你做了什么来解决它。写作“问题是固定的”并不算作答案。

就此而言,如果你不喜欢我在这里的答案,你想写自己的答案,你仍然可以这样做。如果您愿意,您甚至可以接受自己的答案,而不是我的答案。只要确保它是一个真正的答案。

相关问题