Copying and Pasting cs Code

In cs, like in almost any computer programming language, reading data from a file can be tricky. You add extra lines of code to tell the computer what to do. Sometimes you can copy and paste these lines from other peoples’ code.

For example, you can follow the pattern in this listing:

         private void Button3_Click(object sender, EventArgs e)
         {
             if (dataGridView1.DataSource == null)
             {
                 MessageBox.Show("Sorry nothing to export into excel sheet..", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                 return;
             }
             int rowsTotal = 0;
             int colsTotal = 0;
             int I = 0;
             int j = 0;
             int iC = 0;
             System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
             Excel.Application xlApp = new Excel.Application();

             try
             {
                 Excel.Workbook excelBook = xlApp.Workbooks.Add();
                 Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelBook.Worksheets[1];
                 xlApp.Visible = true;

                 rowsTotal = dataGridView1.RowCount;
                 colsTotal = dataGridView1.Columns.Count - 1;
                 var _with1 = excelWorksheet;
                 _with1.Cells.Select();
                 _with1.Cells.Delete();
                 for (iC = 0; iC <= colsTotal; iC++)
                 {
                     _with1.Cells[1, iC + 1].Value = dataGridView1.Columns[iC].HeaderText;
                 }
                 for (I = 0; I <= rowsTotal - 1; I++)
                 {
                     for (j = 0; j <= colsTotal; j++)
                     {
                         _with1.Cells[I + 2, j + 1].value = dataGridView1.Rows[I].Cells[j].Value;
                     }
                 }
                 _with1.Rows["1:1"].Font.FontStyle = "Bold";
                 _with1.Rows["1:1"].Font.Size = 12;

                 _with1.Cells.Columns.AutoFit();
                 _with1.Cells.Select();
                 _with1.Cells.EntireColumn.AutoFit();
                 _with1.Cells[1, 1].Select();
             }
             catch (Exception ex)
             {
                 MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
             finally
             {
                 //RELEASE ALLOACTED RESOURCES
                 System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
                 xlApp = null;
             }
         }