Tuesday 5 April 2011

Export Grid view to PDF

How to Export Grid view to PDF?
Gridview data is Export to PDF document with help of free itextsharp reference.

Download itextsharp.dll file from below link

After download add this itextsharp.dll reference into your project
Select Project Name in solution explorer ->Right click select add reference ->select Browse tab->and choose your itextsharp.dll location click Ok button. Then write below code in your web page.
Client Side
I placed one Grid View and button under form tag
<asp:GridView ID="GridView1" runat="server">
</asp:GridView><br />
<asp:Button ID="btnExport" runat="server" Text="Export to PDF"
            onclick="btnExport_Click"/>

Server Side
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Data;
using System.IO;
using System.Data.SqlClient;

public partial class Export_PDF : System.Web.UI.Page
{
    //Server connection detail
    SqlConnection sqlcon = new SqlConnection(@"Server=RAVI\SQLEXPRESS;database=test;uid=xxxx;pwd=yyyy;");
    SqlCommand sqlcmd = new SqlCommand();
    DataTable dt = new DataTable();
    SqlDataAdapter da = new SqlDataAdapter();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindGrid();
        }
    }

    void BindGrid()
    {
        sqlcmd = new SqlCommand("select * from emp1", sqlcon);
        sqlcon.Open();
        da = new SqlDataAdapter(sqlcmd);
        da.Fill(dt);
        //store this data table value in session for export as pdf in future
        Session["Export_Table"] = dt;
        GridView1.DataSource = dt;
        GridView1.DataBind();
        sqlcon.Close();
    }

    protected void btnExport_Click(object sender, EventArgs e)
    {      
        if (Session["Export_Table"] != null)
        {
            ExportToPdf(Session["Export_Table"] as DataTable);
        }
        else {
            Response.Write("No data to Export!");
        }
    }

    public void ExportToPdf(DataTable ExDataTable)
    {
        //Here set page size as A4
       
        Document pdfDoc = new Document(PageSize.A4, 10, 10, 10, 10);

        try
        {
            PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);
            pdfDoc.Open();
          
            //Header Logo path
            string imageFilePath = Server.MapPath("~/images/Header.jpg");
            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageFilePath);

            //Set Height and width for your Image Header
            image.ScaleToFit(80f, 60f);

            //Here I give space before image
            image.SpacingBefore = 0f;

            //Here I give space after image
            image.SpacingAfter = 1f;
            image.Alignment = Element.HEADER;

            //Add Header image to PDF Document
            pdfDoc.Add(image);

            //Set Font Properties for PDF File
            Font fnt = FontFactory.GetFont("Times New Roman", 12);
            DataTable dt = ExDataTable;

            if (dt != null)
            {
               
                PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);
                PdfPCell PdfPCell = null;
               
                //Here we create PDF file tables

                for (int rows = 0; rows < dt.Rows.Count; rows++)
                {
                    for (int column = 0; column < dt.Columns.Count; column++)
                    {
                        PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), fnt)));
                        PdfTable.AddCell(PdfPCell);
                    }
                }

                // Finally Add pdf table to the document
                pdfDoc.Add(PdfTable);
            }

            pdfDoc.Close();
           
            Response.ContentType = "application/pdf";
           
            //Set default file Name as current datetime
            Response.AddHeader("content-disposition", "attachment; filename=" + DateTime.Now.ToString("yyyyMMdd") + ".pdf");

            System.Web.HttpContext.Current.Response.Write(pdfDoc);

            Response.Flush();
            Response.End();
         
        }     
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }  
  
}

Monday 4 April 2011

Bind Grid view without using Database Table


How to bind data on grid view without using Database?

Yes possible to bind data on Gridview without  using database. Create one data table, add columns and its values through code and bind it in the grid view.
Refer below code for the example
Client Side
Place grid view inside of form tag
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
 <asp:BoundField HeaderText="Employee No" DataField="Empno" />
 <asp:BoundField HeaderText="Employee Name" DataField="Empname" />
 <asp:BoundField HeaderText="Employee Salary" DataField="Salary" />
</Columns>
</asp:GridView>
Server Side
using System.Data;
using System.Data.SqlClient;

public partial class BindGrid_WithoutDB : System.Web.UI.Page
{
    DataTable dt = new DataTable();
    DataRow dr;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindGrid();
        }
    }
    void BindGrid()
    {
        dt.Columns.Add("Empno");
        dt.Columns.Add("Empname");
        dt.Columns.Add("Salary");
        dr = dt.NewRow();
        dr["Empno"] = "101";
        dr["Empname"] = "Ravindran";
        dr["Salary"] = "25000";
        dt.Rows.Add(dr);
        if (dt.Rows.Count > 0)
        {
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
}

Output:


How to use #region in C# code?

How to use #region in C# code?
Region is used to group of your specified code. We can use region block in any number of times in our server side code.
Advantages:
Easily understood code block by new user when refer your project first time.
Copy to particular block is easy when you use region in that block.
How to code for region block?
You can put your code in side of block region syntax block
#region set any region name
//Your code
#endregion
Example for without using Region Block in C# code
using System.Data;
using System.Data.SqlClient;

public partial class Default2 : System.Web.UI.Page
{
    SqlConnection sqlcon = new SqlConnection(@"Server=RAVI\SQLEXPRESS;database=test;uid=xxxx;pwd=yyyy;");
    SqlCommand sqlcmd = new SqlCommand();
    SqlDataAdapter da = new SqlDataAdapter();
    DataTable dt = new DataTable();

    protected void Page_Load(object sender, EventArgs e)
    {
        BindGrid();
    }
   void BindGrid()
    {
        try
        {
            sqlcon.Open();
            sqlcmd = new SqlCommand("select * from emp", sqlcon);
            da = new SqlDataAdapter(sqlcmd);
            da.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }

        catch (Exception e)
        {
            Response.Write(e.ToString());
        }
        finally {
            sqlcon.Close();
        }

    }
}

Example for with use of Region Block in C# code
using System.Data;
using System.Data.SqlClient;

public partial class Default2 : System.Web.UI.Page
{
   #region Declaration part
    SqlConnection sqlcon = new SqlConnection(@"Server=System3\SQLEXPRESS;database=test;uid=ravindran;pwd=srirangam;");
    SqlCommand sqlcmd = new SqlCommand();
    SqlDataAdapter da = new SqlDataAdapter();
    DataTable dt = new DataTable();
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        BindGrid();
    }
 
#region Bind data from SQL table to GridView
    void BindGrid()
    {
        try
        {
            sqlcon.Open();
            sqlcmd = new SqlCommand("select * from emp", sqlcon);
            da = new SqlDataAdapter(sqlcmd);
            da.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }

        catch (Exception e)
        {
            Response.Write(e.ToString());
        }
        finally {
            sqlcon.Close();
        }

    }
   #endregion
}

After add region in your code then show simplify your code use of region blocks