Tuesday, January 17, 2017

Difference between Singleton Class and Static Class


Static Class:
  1. You cannot create the instance of static class.

  2. Loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
  3. We cannot inherit Static class to another Static class in C#.
  4. We cannot pass the static class to method.
Singleton:
  1. You can create one instance of the object and reuse it.

  2. Singleton instance is created for the first time when the user requested.

  3. Singleton class can have constructor.

  4. You can create the object of singleton class and pass it to method.

  5. We can dispose the objects of a singleton class but not of static class.

Wednesday, December 7, 2016

Dynamic columns width in RDLC

I am trying to generate a RDLC report in ASP.NET where the columns of my Dataset will be dynamic and determined only at run time.

 public DataTable GetTable(int type)
        {
            DataTable table = new DataTable();
            if (type == 1)
            {
                table.Columns.Add("Dosage", typeof(int));
                table.Columns.Add("Drug", typeof(string));
                table.Columns.Add("Patient", typeof(string));
                table.Columns.Add("Date", typeof(DateTime));
                table.Columns.Add("testColumn", typeof(DateTime));

                // Here we add five DataRows.
                table.Rows.Add(25, "Indocin", "Jignesh", DateTime.Now);
                table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
                table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
                table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
                table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
            }
            else
            {
                table.Columns.Add("Dosage", typeof(int));
                table.Columns.Add("Patient", typeof(string));
                table.Columns.Add("Date", typeof(DateTime));

                // Here we add five DataRows.
                table.Rows.Add(25, "Jignesh", DateTime.Now);
                table.Rows.Add(50, "Sam", DateTime.Now);
                table.Rows.Add(10, "Christoff", DateTime.Now);
                table.Rows.Add(21, "Janet", DateTime.Now);
                table.Rows.Add(100, "Melanie", DateTime.Now);
            }

            return table;
        }



  public ActionResult GenerateReportList()
        {
            var reportDataSource = new List();
            var localReport = new LocalReport();
            var path = GeLocCommon.ReportCommonPath + GeLocCommon.RightsReport;
            path = Server.MapPath(path + GeLocCommon.M02_details);
            if (System.IO.File.Exists(path))
            {
                localReport.ReportPath = path;
            }
            else
            {
                return RedirectToAction("Index");
            }

            var data = GetTable(1);
            reportDataSource.Add(new ReportDataSource
            {
                Name = GeLocCommon.RightsDetailDataSet,
                Value = data
            });


            localReport = localReport.LocalizeReport();
            var totalWidth = (float)7.215;
            totalWidth = totalWidth / data.Columns.Count;
            var resizedcolumns = "< TablixColumns >";
            for (int i = 0; i < data.Columns.Count; i++)
            {
                resizedcolumns = resizedcolumns + "<  TablixColumn > < Width>" + totalWidth + "in</ Width>< /TablixColumn  >";
            }

            for (int i = data.Columns.Count; i < 5; i++)
            {
                resizedcolumns = resizedcolumns + "< TablixColumn ><  Width >0.1in</  Width  ><  /TablixColumn  >";
            }

            resizedcolumns = resizedcolumns + "<  /TablixColumns  >";
            resizedcolumns = resizedcolumns.ToString().Replace(",", ".");
            var rptxml = System.IO.File.ReadAllText(path);
            var start = rptxml.IndexOf("< TablixColumns >");
            var end = rptxml.IndexOf("< /TablixColumns  >") + " < /  TablixColumns  >".Length;
            rptxml = rptxml.Substring(0, start) + resizedcolumns + rptxml.Substring(end);
            System.IO.TextReader tr = new System.IO.StringReader(rptxml);
            localReport.LoadReportDefinition(tr);
            tr.Close();
            var downloadedFileName = GeLocCommon.RightsReportTemplate + 1 + GeLocCommon.SeperatorDash + DateTime.Now.ToString(GeLocCommon.ReportGeneratedDateFormat) + GeLocCommon.SeperatorDot + "pdf";
            string mimeType;
            return File(localReport.GenerateReport(ExportDataType.Pdf.ToString(), reportDataSource, null, out mimeType, false), mimeType, downloadedFileName);
        }




 

Thursday, April 28, 2016

Export to excel using jquery for JQgrid

step 1 :create  ExportGridToExcel.ashx for open file

 public class ExportGridToExcel : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string tabData = context.Request["excelData"];

            DataTable dt = ConvertCsvData(tabData);
            if (dt == null)
            {
                return;
            }
            string excelFilename = context.Request["filename"];
            if (File.Exists(excelFilename))
                File.Delete(excelFilename);

            string FileName = CreateExcel.CreateExcelDocument(dt, excelFilename, context.Response); ;
            string FilePath = "ExcelFiles//" + FileName;
           

           
            context.Response.Clear();
            context.Response.Buffer = true;

            context.Response.AddHeader("content-disposition", string.Format("attechment; filename={0}", FileName));
            string strFilePath = context.Request.PhysicalApplicationPath + FilePath;
            string strExtension = System.IO.Path.GetExtension(strFilePath);
            if (strExtension.Equals(".xls", StringComparison.InvariantCulture) || strExtension.Equals(".csv", StringComparison.InvariantCulture) || strExtension.Equals(".xlsx", StringComparison.InvariantCulture))
            {
                context.Response.ContentType = "application/ms-excel";
            }
            else if (strExtension.Equals(".pdf", StringComparison.InvariantCulture))
            {
                context.Response.ContentType = "application/pdf";
            }

            context.Response.WriteFile(strFilePath);
            context.Response.End();

        }

        private DataTable ConvertCsvData(string CSVdata)
        {
            //  Convert a tab-separated set of data into a DataTable, ready for our C# CreateExcelFile libraries
            //  to turn into an Excel file.
            //
            DataTable dt = new DataTable();
            try
            {
                System.Diagnostics.Trace.WriteLine(CSVdata);

                string[] Lines = CSVdata.Split(new char[] { '\r', '\n' });
                if (Lines == null)
                    return dt;
                if (Lines.GetLength(0) == 0)
                    return dt;

                string[] HeaderText = Lines[0].Split('\t');

                int numOfColumns = HeaderText.Count();


                foreach (string header in HeaderText)
                    dt.Columns.Add(header, typeof(string));

                DataRow Row;
                for (int i = 1; i < Lines.GetLength(0); i++)
                {
                    string[] Fields = Lines[i].Split('\t');
                    if (Fields.GetLength(0) == numOfColumns)
                    {
                        Row = dt.NewRow();
                        for (int f = 0; f < numOfColumns; f++)
                        {
                            if (Fields[f] == "0")
                                Row[f] = "";
                            else
                                Row[f] = Fields[f].Replace("null", "");

                            Row[f] = Row[f].ToString().Replace("", "");
                            Row[f] = Row[f].ToString().Replace("
", ",");
                        }
                        dt.Rows.Add(Row);
                    }
                }

                return dt;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine("An exception occurred: " + ex.Message);
                return null;
            }
        }
   
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

   public class CreateExcel
    {
        ///

        /// Create an Excel file, and write it out to a MemoryStream (rather than directly to a file)
        ///

        /// DataTable containing the data to be written to the Excel.
        /// The filename (without a path) to call the new Excel file.
        /// HttpResponse of the current page.
        /// True if it was created succesfully, otherwise false.
        public static string  CreateExcelDocument(DataTable dt, string filename, System.Web.HttpResponse Response)
        {
            try
            {

               return CreateExcelDocumentAsStream(dt, filename, Response);
               
            }
            catch (Exception ex)
            {

                return "";
            }
        }


        ///

        /// Create an Excel file, and write it out to a MemoryStream (rather than directly to a file)
        ///

        /// DataSet containing the data to be written to the Excel.
        /// The filename (without a path) to call the new Excel file.
        /// HttpResponse of the current page.
        /// Either a MemoryStream, or NULL if something goes wrong.
        public static string  CreateExcelDocumentAsStream(DataTable dt, string filename, System.Web.HttpResponse Response)
        {
            try
            {
                Random rnd = new Random();
                string _strFile = DateTime.Now.ToString("ddMMyyyy") + "_" + rnd.Next(0, 9999) + ".xlsx";
                FileInfo newFile = new FileInfo(HttpContext.Current.Server.MapPath("~/ExcelFiles/" + _strFile));
                if (newFile.Exists)
                {
                    newFile.Delete();  // ensures we create a new workbook
                    newFile = new FileInfo(_strFile);
                }

                ExcelPackage xlPackage = new ExcelPackage(newFile);
                ExcelWorksheet xlWorkSheet = xlPackage.Workbook.Worksheets.Add("DefaultFormat");
                int _RowID = 1;
                xlWorkSheet.Cells.Style.Numberformat.Format = "@";
                xlWorkSheet.Cells.Style.Numberformat.Format = "General";
                int _Cell = 1;
                for (int i = 1; i <= dt.Columns.Count; i++)
                {
                    xlWorkSheet.Cells[_RowID, _Cell].Value = dt.Columns[i - 1].ToString();
                    xlWorkSheet.Cells[_RowID, _Cell].Style.WrapText = true;
                    xlWorkSheet.Cells[_RowID, _Cell].Style.Font.Bold = true;
                    xlWorkSheet.Cells[_RowID, _Cell].Style.Border.Top.Style = ExcelBorderStyle.Thin;
                    xlWorkSheet.Cells[_RowID, _Cell].Style.Border.Left.Style = ExcelBorderStyle.Thin;
                    xlWorkSheet.Cells[_RowID, _Cell].Style.Border.Right.Style = ExcelBorderStyle.Thin;
                    xlWorkSheet.Cells[_RowID, _Cell].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
                    xlWorkSheet.Cells[_RowID, _Cell].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                    xlWorkSheet.Cells[_RowID, _Cell].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                    xlWorkSheet.Cells[_RowID, _Cell].Style.Numberformat.Format = "@";
                    xlWorkSheet.Cells[_RowID, _Cell].Style.Numberformat.Format = "General";
                    _Cell++;

                }
                _RowID++;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                     _Cell = 1;
                    for (int ji = 0; ji < dt.Columns.Count; ji++)
                    {
                        xlWorkSheet.Cells[_RowID, _Cell].Value = Convert.ToString(dt.Rows[i][ji]);
                        xlWorkSheet.Cells[_RowID, _Cell].Style.Border.Top.Style = ExcelBorderStyle.Thin;
                        xlWorkSheet.Cells[_RowID, _Cell].Style.Border.Left.Style = ExcelBorderStyle.Thin;
                        xlWorkSheet.Cells[_RowID, _Cell].Style.Border.Right.Style = ExcelBorderStyle.Thin;
                        xlWorkSheet.Cells[_RowID, _Cell].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
                        xlWorkSheet.Cells[_RowID, _Cell].Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
                        xlWorkSheet.Cells[_RowID, _Cell].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                        xlWorkSheet.Cells[_RowID, _Cell].Style.Numberformat.Format = "@";
                        xlWorkSheet.Cells[_RowID, _Cell].Style.Numberformat.Format = "General";
                        _Cell++;
                    }
                    _RowID++;
                }
                xlWorkSheet.Cells.AutoFitColumns();
                xlPackage.Save();
                xlPackage.Dispose();
                return _strFile;
            }
            catch (Exception ex)
            {

                return "";
            }
        }

    }


Step 2 Js file

function ExportJQGridDataToExcel(tableCtrl, excelFilename) {
    //  Export the data from our jqGrid into a (real !) Excel .xlsx file.
    //
    //  We'll build up a (very large?) tab-separated string containing the data to be exported, then POST them
    //  off to a .ashx handler, which creates the Excel file.
    debugger
    var allJQGridData = $(tableCtrl).jqGrid('getGridParam', 'data');

    var jqgridRowIDs = $(tableCtrl).getDataIDs();                // Fetch the RowIDs for this grid
    var headerData = $(tableCtrl).getRowData(jqgridRowIDs[0]);   // Fetch the list of "name" values in our colModel

    //  For each visible column in our jqGrid, fetch it's Name, and it's Header-Text value
    var columnNames = new Array();       //  The "name" values from our jqGrid colModel
    var columnHeaders = new Array();     //  The Header-Text, from the jqGrid "colNames" section
    var inx = 0;
    var allColumnNames = $(tableCtrl).jqGrid('getGridParam', 'colNames');

    for (var headerValue in headerData) {
        //  If this column ISN'T hidden, and DOES have a column-name, then we'll export its data to Excel.
        var isColumnHidden = $(tableCtrl).jqGrid("getColProp", headerValue).hidden;
        if (!isColumnHidden && headerValue != null) {
            columnNames.push(headerValue);
            columnHeaders.push(allColumnNames[inx]);
        }
        inx++;
    }

    //  We now need to build up a (potentially very long) tab-separated string containing all of the data (and a header row)
    //  which we'll want to export to Excel.

    //  First, let's append the header row...
    var excelData = '';
    for (var k = 0; k < columnNames.length; k++) {
        excelData += columnHeaders[k] + "\t";
    }
    excelData = removeLastChar(excelData) + "\r\n";

    //  ..then each row of data to be exported.
    var cellValue = '';
    for (i = 0; i < allJQGridData.length; i++) {

        var data = allJQGridData[i];

        for (var j = 0; j < columnNames.length; j++) {

            // Fetch one jqGrid cell's data, but make sure it's a string
            cellValue = '' + data[columnNames[j]];

            if (cellValue == null)
                excelData += "\t";
            else {
                if (cellValue.indexOf("a href") > -1) {
                    //  Some of my cells have a jqGrid cell with a formatter in them, making them hyperlinks.
                    //  We don't want to export the " " tags to our Excel file, just the cell's text.
                    cellValue = $(cellValue).text();
                }
                //  Make sure we are able to POST data containing apostrophes in it
                cellValue = cellValue.replace(/'/g, "'");

                excelData += cellValue + "\t";
            }
        }
        excelData = removeLastChar(excelData) + "\r\n";
    }
    //  Now, we need to POST our Excel Data to our .ashx file *and* redirect to the .ashx file.
    postAndRedirect("../../Handlers/ExportGridToExcel.ashx?filename=" + excelFilename, { excelData: excelData });
}

function removeLastChar(str) {
    //  Remove the last character from a string
    return str.substring(0, str.length - 1);
}

function postAndRedirect(url, postData) {
    //  Redirect to a URL, and POST some data to it.
    //  Taken from:
    //  http://stackoverflow.com/questions/8389646/send-post-data-on-redirect-with-javascript-jquery
    //
    var postFormStr = "
\n";

    for (var key in postData) {
        if (postData.hasOwnProperty(key)) {
            postFormStr += "";
        }
    }

    postFormStr += "
";

    var formElement = $(postFormStr);

    $('body').append(formElement);
    $(formElement).submit();
}


step 3  Add js code in jqgriid


   $("#jqTable").navButtonAdd('#jqTablePager', {
        title: "Export to Excel",
        buttonicon: "ace-icon fa fa-file-excel-o",
        caption: "",
        onClickButton: function () {
            ExportJQGridDataToExcel("#jqTable", "ExcelName.xlsx");
        },
        position: "last"
    });
if data not display in excel please set below property in JqGrid
loadonce: true,


Thanks

Monday, April 25, 2016

Upload document using Ajax call

 submitHandler: function (form) {
                var $form = $("#frmQuestion"), formData = new FormData(), params = $form.serializeArray();
                $.each(params, function (i, val) {
                    formData.append(val.name, val.value);
                });

                var files = $("input[Type='file']");
                for (var i = 0; i < files.length; i++) {
                    formData.append(files[i].name, $('#' + files[i].id).get(0).files[0]);
                             }

               
                $.ajax({
                    url: '/Questions/SaveQuestion',
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    type: 'POST',
                    mimeType: "multipart/form-data",
                    beforeSend: function () { ShowCustomLoading(true); },
                    complete: function () { ShowCustomLoading(false); },
                    success: function (datas) {

                        var data = JSON.parse(datas)
                        if (data.Key == true) {
                            new PNotify({
                                text: data.Value,
                                delay: 1500,
                                type: 'success'
                            });
                            $("#divlist").show();
                            $("#divAdd").hide();
                            $("#jqTable").trigger('reloadGrid');
                        }
                        else {
                            new PNotify({
                                text: data.Value,
                                delay: 1500,
                                type: 'error'
                            });
                        }
                    }
                });
            }

Thursday, May 3, 2012

Exporting to Word, Excel ,pdf and CSV

In this article, I will explain how to export GridView to Word, Excel, PDF and CSV formats.
Exporting to Word, Excel and CSV can be easily achieved using ASP.Net without any third party tools, but for exporting GridView to PDF I am using iTextSharp which is a free library for exporting html to PDF.
To start with I have a GridView in which I am showing Customers records from the NorthWind Database.
The HTML markup of the GridView is as shown below
<asp:GridView ID="GridView1" runat="server"
    AutoGenerateColumns = "false" Font-Names = "Arial"
    Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B" 
    HeaderStyle-BackColor = "green" AllowPaging ="true"  
    OnPageIndexChanging = "OnPaging" >
   <Columns>
    <asp:BoundField ItemStyle-Width = "150px" DataField = "CustomerID"
    HeaderText = "CustomerID" />
    <asp:BoundField ItemStyle-Width = "150px" DataField = "City"
    HeaderText = "City"/>
    <asp:BoundField ItemStyle-Width = "150px" DataField = "Country"
    HeaderText = "Country"/>
    <asp:BoundField ItemStyle-Width = "150px" DataField = "PostalCode"
    HeaderText = "PostalCode"/>
   Columns>
asp:GridView>
In the figure below the GridView is shown with four buttons
1.     Export To Word
2.     Export To Excel
3.     Export To PDF
4.     Export To CSV


GridView with Sample Data


Export to Microsoft Word Format
C#
protected void btnExportWord_Click(object sender, EventArgs e)
{
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition",
    "attachment;filename=GridViewExport.doc");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-word ";
    StringWriter sw= new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    GridView1.AllowPaging = false;
    GridView1.DataBind();
    GridView1.RenderControl(hw);
    Response.Output.Write(sw.ToString());
    Response.Flush();
    Response.End();
}
VB.Net
Protected Sub btnExportWord_Click(ByVal sender As Object,
    ByVal e As EventArgs)
        Response.Clear()
        Response.Buffer = True
        Response.AddHeader("content-disposition",
        "attachment;filename=GridViewExport.doc")
        Response.Charset = ""
        Response.ContentType = "application/vnd.ms-word "
        Dim sw As New StringWriter()
        Dim hw As New HtmlTextWriter(sw)
        GridView1.AllowPaging = False
        GridView1.DataBind()
        GridView1.RenderControl(hw)
        Response.Output.Write(sw.ToString())
        Response.Flush()
        Response.End()
    End Sub
The above function renders the GridView contents as Microsoft Word format. You will notice I have disabled paging before exporting, so that all the pages are exported.
The Output Exported File


GridView data exported to Word Document


Export to Microsoft Excel Format
For exporting the document to Excel if you do it directly as done in case of word the row background color is applied throughout to all the columns in the Excel Sheet hence in order to avoid it. I have done a workaround below.
First I am changing the background color of each row back to white.
Then I am applying the background color to each individual cell rather than the whole row. Thus when you export now you will notice that the formatting is applied only to the GridView cells and not all
Also I am applying textmode style class to all cells and then adding the style CSS class to the GridView before rendering it, this ensures that all the contents of GridView are rendered as text.

protected void btnExportExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
//Change the Header Row back to white color
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Apply style to Individual Cells
GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[3].Style.Add("background-color", "green");  
for (int i = 0; i < GridView1.Rows.Count;i++ )
{
    GridViewRow row = GridView1.Rows[i];
    //Change Color back to white
    row.BackColor = System.Drawing.Color.White;
    //Apply text style to each Row
    row.Attributes.Add("class", "textmode");
    //Apply style to Individual Cells of Alternating Row
    if (i % 2 != 0)
    {
        row.Cells[0].Style.Add("background-color", "#C2D69B");
        row.Cells[1].Style.Add("background-color", "#C2D69B");
        row.Cells[2].Style.Add("background-color", "#C2D69B");
        row.Cells[3].Style.Add("background-color", "#C2D69B");  
    }
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = @"";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
VB.Net
Protected Sub btnExportExcel_Click(ByVal sender As Object,
ByVal e As EventArgs)
  Response.Clear()
  Response.Buffer = True
  Response.AddHeader("content-disposition",
  "attachment;filename=GridViewExport.xls")
  Response.Charset = ""
  Response.ContentType = "application/vnd.ms-excel"
 
  Dim sw As New StringWriter()
  Dim hw As New HtmlTextWriter(sw)
  GridView1.AllowPaging = False
  GridView1.DataBind()
  'Change the Header Row back to white color
  GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF")
  'Apply style to Individual Cells
  GridView1.HeaderRow.Cells(0).Style.Add("background-color", "green")
  GridView1.HeaderRow.Cells(1).Style.Add("background-color", "green")
  GridView1.HeaderRow.Cells(2).Style.Add("background-color", "green")
  GridView1.HeaderRow.Cells(3).Style.Add("background-color", "green")
  For i As Integer = 0 To GridView1.Rows.Count - 1
   Dim row As GridViewRow = GridView1.Rows(i)
   'Change Color back to white
   row.BackColor = System.Drawing.Color.White
   'Apply text style to each Row
   row.Attributes.Add("class", "textmode")
   'Apply style to Individual Cells of Alternating Row
   If i Mod 2 <> 0 Then
    row.Cells(0).Style.Add("background-color", "#C2D69B")
    row.Cells(1).Style.Add("background-color", "#C2D69B")
    row.Cells(2).Style.Add("background-color", "#C2D69B")
    row.Cells(3).Style.Add("background-color", "#C2D69B")
   End If
  Next
  GridView1.RenderControl(hw)
  'style to format numbers to string
  Dim style As String = ""
  Response.Write(style)
  Response.Output.Write(sw.ToString())
  Response.Flush()
  Response.End()
End Sub
The Output Exported File


GridView data exported to Excel Document


Export to Portable Document Format
For exporting the GridView to PDF I am using the iTextSharp Library. You will need to Add Reference for the iTextSharp Library in your Website.
Then import the following Namespaces
C#
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
VB.Net
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.text.html
Imports iTextSharp.text.html.simpleparser
By default the iTextSharp Library does not support background color of table cells or table rows
Hence when you render it as PDF your GridView is rendered without any formatting.
Recently I read an article on hamang.net where the author has provided the snippet to modify the iTextSharp so that it exports the HTML with background color.
For this tutorial, I have already modified the iTextSharp Library DLL so that the GridView is rendered with all the background color used. You can refer the code for exporting GridView to PDF below
              
C#
protected void btnExportPDF_Click(object sender, EventArgs e)
{
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition",
     "attachment;filename=GridViewExport.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    GridView1.AllowPaging = false;
    GridView1.DataBind();
    GridView1.RenderControl(hw);
    StringReader sr = new StringReader(sw.ToString());
    Document pdfDoc = new Document(PageSize.A4, 10f,10f,10f,0f);
    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
    pdfDoc.Open();
    htmlparser.Parse(sr);
    pdfDoc.Close();
    Response.Write(pdfDoc);
    Response.End(); 
}
VB.Net
Protected Sub btnExportPDF_Click(ByVal sender As Object,
ByVal e As EventArgs)
 Response.ContentType = "application/pdf"
 Response.AddHeader("content-disposition",
 "attachment;filename=GridViewExport.pdf")
 Response.Cache.SetCacheability(HttpCacheability.NoCache)
 Dim sw As New StringWriter()
 Dim hw As New HtmlTextWriter(sw)
 GridView1.AllowPaging = False
 GridView1.DataBind()
 GridView1.RenderControl(hw)
 Dim sr As New StringReader(sw.ToString())
 Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F)
 Dim htmlparser As New HTMLWorker(pdfDoc)
 PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
 pdfDoc.Open()
 htmlparser.Parse(sr)
 pdfDoc.Close()
 Response.Write(pdfDoc)
 Response.End()
End Sub
The Output Exported File


GridView data exported to PDF Document


Export to Text/CSV
Finally comes exporting GridView to CSV or Text File delimited by a separator like comma.
To export the GridView as CSV, I am running a two for loops. While looping through the GridView columns and appending comma after each column and while looping through rows appending new line character. Refer the code below.
C#
protected void btnExportCSV_Click(object sender, EventArgs e)
{
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition",
     "attachment;filename=GridViewExport.csv");
    Response.Charset = "";
    Response.ContentType = "application/text";
    GridView1.AllowPaging = false;
    GridView1.DataBind();
    StringBuilder sb = new StringBuilder();
    for (int k = 0; k < GridView1.Columns.Count; k++)
    {
        //add separator
        sb.Append(GridView1.Columns[k].HeaderText + ',');
    }
    //append new line
    sb.Append("\r\n");
    for (int i = 0; i < GridView1.Rows.Count; i++)
    {
        for (int k = 0; k < GridView1.Columns.Count; k++)
        {
            //add separator
            sb.Append(GridView1.Rows[i].Cells[k].Text + ',');
        }
        //append new line
        sb.Append("\r\n");
    }
    Response.Output.Write(sb.ToString());
    Response.Flush();
    Response.End();
}
      
VB.Net
Protected Sub btnExportCSV_Click(ByVal sender As Object,
ByVal e As EventArgs)
 Response.Clear()
 Response.Buffer = True
 Response.AddHeader("content-disposition",
 "attachment;filename=GridViewExport.csv")
 Response.Charset = ""
 Response.ContentType = "application/text"
 GridView1.AllowPaging = False
 GridView1.DataBind()
 Dim sb As New StringBuilder()
 For k As Integer = 0 To GridView1.Columns.Count - 1
  'add separator
  sb.Append(GridView1.Columns(k).HeaderText + ","c)
 Next
 'append new line
 sb.Append(vbCr & vbLf)
 For i As Integer = 0 To GridView1.Rows.Count - 1
  For k As Integer = 0 To GridView1.Columns.Count - 1
   'add separator
   sb.Append(GridView1.Rows(i).Cells(k).Text + ","c)
  Next
  'append new line
  sb.Append(vbCr & vbLf)
 Next
 Response.Output.Write(sb.ToString())
 Response.Flush()
 Response.End()
End Sub
The Output Exported File


GridView data exported to CSV File


When you run the application first time and click export you might receive the following error


Error encountered when you click export


To avoid the error you will need to add this event which ensures that the GridView is Rendered before exporting.
  
C#
public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}
VB.Net
Public Overloads Overrides Sub VerifyRenderingInServerForm
(ByVal control As Control)
    ' Verifies that the control is rendered
End Sub