473,471 Members | 2,175 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

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

15 New Member
Hi Everyone,

I'm getting Index was out of range error while taking print from Gridview data.

Here is my code can anyone tell me what's wrong with my code?

Expand|Select|Wrap|Line Numbers
  1. public partial class Form1 : Form
  2.     {       #region Member Variables
  3.         StringFormat strFormat; //Used to format the grid rows.
  4.         ArrayList arrColumnLefts = new ArrayList();//Used to save left coordinates of columns
  5.         ArrayList arrColumnWidths = new ArrayList();//Used to save column widths
  6.         int iCellHeight = 0; //Used to get/set the datagridview cell height
  7.         int iTotalWidth = 0; //
  8.         int iRow = 0;//Used as counter
  9.         bool bFirstPage = false; //Used to check whether we are printing first page
  10.         bool bNewPage = false;// Used to check whether we are printing a new page
  11.         int iHeaderHeight = 0; //Used for the header height
  12.         #endregion
  13.  Code Which I've written under Print button method:
  14.  
  15.  private void btnprint_Click(object sender, EventArgs e)
  16.         {
  17.             //Open the print dialog
  18.             PrintDialog printDialog = new PrintDialog();
  19.             printDialog.Document = printDocument1; ;
  20.             printDialog.UseEXDialog = true;
  21.             //Get the document
  22.             if (DialogResult.OK == printDialog.ShowDialog())
  23.             {
  24.                 printDocument1.DocumentName = "Test Page Print";
  25.                 printDocument1.Print();
  26.             }
  27.  
  28.        }
  29.  
  30. Code which I've written under printdocument control method:
  31.  
  32. private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
  33.         {
  34.             try
  35.             {
  36.                 //Set the left margin
  37.                 int iLeftMargin = e.MarginBounds.Left;
  38.                 //Set the top margin
  39.                 int iTopMargin = e.MarginBounds.Top;
  40.                 //Whether more pages have to print or not
  41.                 bool bMorePagesToPrint = false;
  42.                 int iTmpWidth = 0;
  43.  
  44.                 //For the first page to print set the cell width and header height
  45.                 if (bFirstPage)
  46.                 {
  47.                     foreach (DataGridViewColumn GridCol in dataGridView1.Columns)
  48.                     {
  49.                         iTmpWidth = (int)(Math.Floor((double)((double)GridCol.Width /
  50.                             (double)iTotalWidth * (double)iTotalWidth *
  51.                             ((double)e.MarginBounds.Width / (double)iTotalWidth))));
  52.  
  53.                         iHeaderHeight = (int)(e.Graphics.MeasureString(GridCol.HeaderText,
  54.                             GridCol.InheritedStyle.Font, iTmpWidth).Height) + 11;
  55.  
  56.                         // Save width and height of headers
  57.                         arrColumnLefts.Add(iLeftMargin);
  58.                         arrColumnWidths.Add(iTmpWidth);
  59.                         iLeftMargin += iTmpWidth;
  60.                     }
  61.                 }
  62.                 //Loop till all the grid rows not get printed
  63.                 while (iRow <= dataGridView1.Rows.Count - 1)
  64.                 {
  65.                     DataGridViewRow GridRow = dataGridView1.Rows[iRow];
  66.                     //Set the cell height
  67.                     iCellHeight = GridRow.Height + 5;
  68.                     int iCount = 0;
  69.                     //Check whether the current page settings allows more rows to print
  70.                     if (iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
  71.                     {
  72.                         bNewPage = true;
  73.                         bFirstPage = false;
  74.                         bMorePagesToPrint = true;
  75.                         break;
  76.                     }
  77.                     else
  78.                     {
  79.                         if (bNewPage)
  80.                         {
  81.                             //Draw Header
  82.                             e.Graphics.DrawString("Customer Summary",
  83.                                 new Font(dataGridView1.Font, FontStyle.Bold),
  84.                                 Brushes.Black, e.MarginBounds.Left,
  85.                                 e.MarginBounds.Top - e.Graphics.MeasureString("Customer Summary",
  86.                                 new Font(dataGridView1.Font, FontStyle.Bold),
  87.                                 e.MarginBounds.Width).Height - 13);
  88.  
  89.                             String strDate = DateTime.Now.ToLongDateString() + " " +
  90.                                 DateTime.Now.ToShortTimeString();
  91.                             //Draw Date
  92.                             e.Graphics.DrawString(strDate,
  93.                                 new Font(dataGridView1.Font, FontStyle.Bold), Brushes.Black,
  94.                                 e.MarginBounds.Left +
  95.                                 (e.MarginBounds.Width - e.Graphics.MeasureString(strDate,
  96.                                 new Font(dataGridView1.Font, FontStyle.Bold),
  97.                                 e.MarginBounds.Width).Width),
  98.                                 e.MarginBounds.Top - e.Graphics.MeasureString("Customer Summary",
  99.                                 new Font(new Font(dataGridView1.Font, FontStyle.Bold),
  100.                                 FontStyle.Bold), e.MarginBounds.Width).Height - 13);
  101.  
  102.                             //Draw Columns                 
  103.                             iTopMargin = e.MarginBounds.Top;
  104.                             foreach (DataGridViewColumn GridCol in dataGridView1.Columns)
  105.                             {
  106.                                 e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
  107.                                     new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
  108.                                     (int)arrColumnWidths[iCount], iHeaderHeight));
  109.  
  110.                                 e.Graphics.DrawRectangle(Pens.Black,
  111.                                     new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
  112.                                     (int)arrColumnWidths[iCount], iHeaderHeight));
  113.  
  114.                                 e.Graphics.DrawString(GridCol.HeaderText,
  115.                                     GridCol.InheritedStyle.Font,
  116.                                     new SolidBrush(GridCol.InheritedStyle.ForeColor),
  117.                                     new RectangleF((int)arrColumnLefts[iCount], iTopMargin,
  118.                                     (int)arrColumnWidths[iCount], iHeaderHeight), strFormat);
  119.                                 iCount++;
  120.                             }
  121.                             bNewPage = false;
  122.                             iTopMargin += iHeaderHeight;
  123.                         }
  124.                         iCount = 0;
  125.                         //Draw Columns Contents                
  126.                         foreach (DataGridViewCell Cel in GridRow.Cells)
  127.                         {
  128.                             if (Cel.Value != null)
  129.                             {
  130.                                 e.Graphics.DrawString(Cel.Value.ToString(),
  131.                                     Cel.InheritedStyle.Font,
  132.                                     new SolidBrush(Cel.InheritedStyle.ForeColor),
  133.                                     new RectangleF((int)arrColumnLefts[iCount],
  134.                                     (float)iTopMargin,
  135.                                     (int)arrColumnWidths[iCount], (float)iCellHeight),
  136.                                     strFormat);
  137.                             }
  138.                             //Drawing Cells Borders 
  139.                             e.Graphics.DrawRectangle(Pens.Black,
  140.                                 new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
  141.                                 (int)arrColumnWidths[iCount], iCellHeight));
  142.                             iCount++;
  143.                         }
  144.                     }
  145.                     iRow++;
  146.                     iTopMargin += iCellHeight;
  147.                 }
  148.                 //If more lines exist, print another page.
  149.                 if (bMorePagesToPrint)
  150.                     e.HasMorePages = true;
  151.                 else
  152.                     e.HasMorePages = false;
  153.             }
  154.             catch (Exception exc)
  155.             {
  156.                 MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK,
  157.                    MessageBoxIcon.Error);
  158.             }
  159.         }
  160. }
Mar 14 '15 #1
0 3820

Sign in to post your reply or Sign up for a free account.

Similar topics

12
by: Brett L. Moore | last post by:
Hi, I have had trouble determining whether the STL list.size() operation is O(1) or O(n). I know the list is a doubly-linked list, so if the size() operation begins at the head, then counts to...
6
by: Joe | last post by:
I have a: vector<string> which contains a few dozen elements. I want to find the index of the element containing a certain string. for example: vector<string> strings;...
16
by: ES Kim | last post by:
"A Book on C" explains a technique to use an arbitrary array index range. int* p = malloc(sizeof(int) * 10) - 1; This way, the allocated array can be accessed with index range 1 ~ 10, not 0 ~...
12
by: pamelafluente | last post by:
Hi guys, Is it possible to get the current index, when iterating with FOR EACH on some collection (implementing ILIST) without using and external counting variable (, that is somehow getting...
2
by: Harry | last post by:
Good Day To all, When i am declaring a array for e.g char ....it means i am declaring array of 45 characters each of which has a maximum,minimum value limit or range...for example in...
1
by: =?Utf-8?B?UnlhbiBBbmRydXM=?= | last post by:
Does the int index of the DataTable.Rows collection place a size limit on how large a datatable can be? If not then how do you index DataTable.Rows for sizes greater than what an int can handle?
1
by: =?Utf-8?B?SkI=?= | last post by:
Hello As I debug the C# code with a break point and by pressing F11 I eventually get a message stating: ContextSwitchDeadlock was detected Message: The CLR has been unable to transition from...
1
by: vivek samantray | last post by:
I have a query.When i try to create a index on one of the table the index gets created but when i take the output it stuill shows "TABLE ACCESS FULL" Please see below what i did QUERY ======...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.