Monday, June 13, 2011

Export Gridview to Word,Excel,Pdf and CVS



using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using System.IO;
using System.Collections;
using System.Net;
using System.Text;

namespace WebApplication1
{
    public partial class Export : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnExportToWord_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();
        }

        protected void btnExportToExcel_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");
            GridView1.HeaderRow.Cells[4].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");
                    row.Cells[4].Style.Add("background-color", "#C2D69B");
                }
            }
            GridView1.RenderControl(hw);

            //style to format numbers to string
            string style = @"<style> .textmode { mso-number-format:\@; } </style>";
            Response.Write(style);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
        }

        protected void btnExportToPDF_Click(object sender, EventArgs e)
        {
            int columnCount = GridView1.Columns.Count;
            int rowCount = GridView1.Rows.Count;
            int tableRows = rowCount + 3;
            iTextSharp.text.Table grdTable =
            new iTextSharp.text.Table(columnCount, tableRows);
            grdTable.BorderWidth = 1;
            grdTable.BorderColor = new Color(0, 0, 255);
            grdTable.Cellpadding = 5;
            grdTable.Cellspacing = 5;

            for (int rowCounter = 0;
            rowCounter < rowCount; rowCounter++)
            {
                for (int columnCounter = 0; columnCounter < columnCount; columnCounter++)
                {
                    string strValue = GridView1.Rows[rowCounter].Cells[columnCounter].Text;
                    grdTable.AddCell(strValue);
                }
            }
            Document Doc = new Document();
            PdfWriter.GetInstance(Doc, Response.OutputStream);
            Doc.Open();
            Doc.Add(grdTable);
            Doc.Close();
            Response.ContentType = "application/pdf";
            Response.AddHeader
            ("content-disposition", "attachment; filename=ArjunSingh.pdf");
            Response.End();

        }


        protected void btnExportToCVS_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();
        }
        public override void VerifyRenderingInServerForm(Control control)
        {
            /* Verifies that the control is rendered */
        }
    }
}

Wednesday, June 8, 2011

Create a 3D chart in ASP.NET 4.0


Creating a 3D chart in ASP.NET 4.0 is a cakewalk! Let us take an example of converting a simple chart to a 3D chart in ASP.NET 4.0

The chart shown below is a simple Column chart

 <asp:Chart ID="Chart1" runat="server" DataSourceID="SqlDataSource1" Height="452px"
            Width="822px"  BackColor="WhiteSmoke" BackGradientStyle="TopBottom"
            BackHatchStyle="DarkDownwardDiagonal">
            <Series>
                <asp:Series Name="Series1" XValueMember="Files_Name" YValueMembers="counts" LabelToolTip="FileName"
                    Palette="BrightPastel" IsValueShownAsLabel="true" YValuesPerPoint="4" IsVisibleInLegend="true"
                    ShadowColor="Black">
                </asp:Series>
            </Series>
            <ChartAreas>
                <asp:ChartArea Name="ChartArea1">
                    <Area3DStyle Enable3D="true" Inclination="10" LightStyle="Realistic" Perspective="15"
                        IsRightAngleAxes="false" IsClustered="false" />
                </asp:ChartArea>
            </ChartAreas>
        </asp:Chart>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:RegistrationConnectionString %>"
            SelectCommand="SELECT     COUNT(*) AS counts, Files_Name
FROM         TrackingInfo
GROUP BY Files_Name">



Wednesday, January 26, 2011

Tree View Using database

Step 1Create two database tables ParentMaster and ChildMaster

Step 2 : Now that we have created our tables, open Microsoft Visual Studio 2005 and create and Asp.net 2.0 WebForm.

Step 3 : Add the following LOC (Line of code) at the start of your programs along with other using keywords.
                   using System.Data.SqlClient;

Step 4 : Place a TreeView control on your WebForm.


          Now double click your page, point to Page_Load event and write fillTree();

                             protected void Page_Load(object sender, EventArgs e)
                               {
                                    fillTree();
                               }



Step 5 : Now the real thing starts. In this step we will populate our TreeView1 control using our two tables ParentMaster and ChildMaster.

     Create a function fillTree()
    
        private void fillTree()
           {
            string connectionstring = ConfigurationManager.ConnectionStrings["your connectionstring name"].ConnectionString;
            SqlConnection mycon = new SqlConnection(connectionstring);
            mycon.Open();
            SqlCommand mycmd = new SqlCommand("Select * from ParentMaster", mycon);
            SqlDataReader dr = mycmd.ExecuteReader();
            mycmd.Dispose();
            string[,] ParentNode = new string[100, 2];
            int count = 0;
            while (dr.Read())
            {
                ParentNode[count,0]=dr.GetValue(dr.GetOrdinal("ParentId")).ToString();
                ParentNode[count++, 1] = dr.GetValue(dr.GetOrdinal("ParentName")).ToString();
            }
            dr.Close();
            for (int loop = 0; loop < count; loop++)
            {
                TreeNode root = new TreeNode();
                root.Text = ParentNode[loop, 1];
                root.NavigateUrl = "Default.aspx";

                SqlCommand childcmd = new SqlCommand("Select * from ChildMaster where ParentId='" + ParentNode[loop, 0] + "'", mycon);
                SqlDataReader childdr = childcmd.ExecuteReader();
                while (childdr.Read())
                {
                    TreeNode croot = new TreeNode();
                    croot.Text = childdr.GetValue(childdr.GetOrdinal("ChildName")).ToString();
                    croot.NavigateUrl = "Grid.aspx";
                    root.ChildNodes.Add(croot);
                }
                childdr.Close();

                TreeView1.Nodes.Add(root);
                TreeView1.CollapseAll();
            }
        }
    }


Also see my other blogs: Reset Table id to zero in sql server
                                                                Get Primary key of gridview on edit commant