Index was out of range.Must be non-negative and less than the size of the collection print gridview
  • Hello
    I have created a sample app to print grid view using Print Dialog in c#.
    I used code from http://web3.codeproject.com/Articles/28046/Printing-of-DataGridView to create the Windows Form app. But it is not working fine. 

    It shows error Index was out of range. Must be non-negative and less than the size of the collection 

    I am having this error at below lines of code. 
     private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
    {
    try
    {
    //Set the left margin
    int iLeftMargin = e.MarginBounds.Left;
    //Set the top margin
    int iTopMargin = e.MarginBounds.Top;
    //Whether more pages have to print or not
    bool bMorePagesToPrint = false;
    int iTmpWidth = 0;

    //For the first page to print set the cell width and header height
    if (bFirstPage)
    {
    foreach (DataGridViewColumn GridCol in dataGridView1.Columns)
    {
    iTmpWidth = (int)(Math.Floor((double)((double)GridCol.Width /
    (double)iTotalWidth * (double)iTotalWidth *
    ((double)e.MarginBounds.Width / (double)iTotalWidth))));

    iHeaderHeight = (int)(e.Graphics.MeasureString(GridCol.HeaderText,
    GridCol.InheritedStyle.Font, iTmpWidth).Height) + 11;

    // Save width and height of headres
    arrColumnLefts.Add(iLeftMargin);
    arrColumnWidths.Add(iTmpWidth);
    iLeftMargin += iTmpWidth;
    }
    }
    //Loop till all the grid rows not get printed
    while (iRow <= dataGridView1.Rows.Count - 1)
    {
    DataGridViewRow GridRow = dataGridView1.Rows[iRow];
    //Set the cell height
    iCellHeight = GridRow.Height + 5;
    int iCount = 0;
    //Check whether the current page settings allo more rows to print
    if (iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
    {
    bNewPage = true;
    bFirstPage = false;
    bMorePagesToPrint = true;
    break;
    }
    else
    {
    if (bNewPage)
    {
    //Draw Header
    e.Graphics.DrawString("Customer Summary", new Font(dataGridView1.Font, FontStyle.Bold),
    Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top -
    e.Graphics.MeasureString("Customer Summary", new Font(dataGridView1.Font,
    FontStyle.Bold), e.MarginBounds.Width).Height - 13);

    String strDate = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString();
    //Draw Date
    e.Graphics.DrawString(strDate, new Font(dataGridView1.Font, FontStyle.Bold),
    Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width -
    e.Graphics.MeasureString(strDate, new Font(dataGridView1.Font,
    FontStyle.Bold), e.MarginBounds.Width).Width), e.MarginBounds.Top -
    e.Graphics.MeasureString("Customer Summary", new Font(new Font(dataGridView1.Font,
    FontStyle.Bold), FontStyle.Bold), e.MarginBounds.Width).Height - 13);

    //Draw Columns
    iTopMargin = e.MarginBounds.Top;
    foreach (DataGridViewColumn GridCol in dataGridView1.Columns)
    {
    e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
    new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
    (int)arrColumnWidths[iCount], iHeaderHeight)); // Compiler is not getting value of arrColumnLefts[iCount]


    e.Graphics.DrawRectangle(Pens.Black,
    new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
    (int)arrColumnWidths[iCount], iHeaderHeight));

    e.Graphics.DrawString(GridCol.HeaderText, GridCol.InheritedStyle.Font,
    new SolidBrush(GridCol.InheritedStyle.ForeColor),
    new RectangleF((int)arrColumnLefts[iCount], iTopMargin,
    (int)arrColumnWidths[iCount], iHeaderHeight), strFormat);
    iCount++;
    }
    bNewPage = false;
    iTopMargin += iHeaderHeight;
    }
    iCount = 0;
    //Draw Columns Contents
    foreach (DataGridViewCell Cel in GridRow.Cells)
    {
    if (Cel.Value != null)
    {
    e.Graphics.DrawString(Cel.Value.ToString(), Cel.InheritedStyle.Font,
    new SolidBrush(Cel.InheritedStyle.ForeColor),
    new RectangleF((int)arrColumnLefts[iCount],(float)iTopMargin,
    (int)arrColumnWidths[iCount], (float)iCellHeight), strFormat);
    }
    //Drawing Cells Borders
    e.Graphics.DrawRectangle(Pens.Black, new Rectangle((int)arrColumnLefts[iCount],
    iTopMargin, (int)arrColumnWidths[iCount], iCellHeight));

    iCount++;
    }
    }
    iRow++;
    iTopMargin += iCellHeight;
    }

    //If more lines exist, print another page.
    if (bMorePagesToPrint)
    e.HasMorePages = true;
    else
    e.HasMorePages = false;
    }
    catch (Exception exc)
    {
    MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    }

    I searched at google but did not find a better answer. Please help me in solving this

    Thanks

  • 1 Comment sorted by
  • Vote Up0Vote Down aftabaftab
    24.50 Karma Accepted Answer
    Hello coder,
    Please double check your grid view bindings, loops, foreach loops and values of all indexes inside Foreach loops. Check by performing debugging by placing a stop at foreach loops, and bindings also check whether compiler is getting values of  iRow <= dataGridView1.Rows.Count  ,  DataGridViewColumn GridCol in dataGridView1.Columns and DataGridViewCell Cel in GridRow.Cells on run time or not. If still you are getting Values of these at run time and still Exception occurs then please see below image and fix Event Binding or Event methods for your document print control. See below image for adding Event methods to your control,

    image

    Hope this solution will work


Howdy, Stranger!

It looks like you're new here. If you want to get involved, or you want to Ask a new Question, Please Login or Create a new Account by Clicking below

Login with Facebook

Tagged

Popular Posts of the Week

    Optimum Creative