How Convert GridView to Word/Excel Asp.Net C# Code

Task : How convert a gridview to Word Document or in Excel Sheet using asp.net/c#  code.

Description: Some time we need to generate different kind of reports & need to save it in Excel or word Document for Local Reference, Or sending to other's. So here I create a code for achieve this task the first one is conversion data into Excel & second one is for Word Document.

// For pdf converstion we can use third party dll like ITextSharp


C# Code : For GridView To Excel

 protected void btn_excel_Click(object sender, EventArgs e)
    {
          string attachment = "attachment; filename=myreport.xls";
          Response.Cache.SetCacheability(HttpCacheability.NoCache);
          Response.AddHeader("content-disposition", attachment);
          Response.ContentType = "application/ms-excel";
          StringWriter swriter = new StringWriter();
          HtmlTextWriter htmlwriter = new HtmlTextWriter(swriter);
 
          // Create a form to contain the gridview(MyGridView)
          HtmlForm mynewform = new HtmlForm();
          MyGridView.Parent.Controls.Add(mynewform);
          mynewform.Attributes["runat"] = "server";
          mynewform.Controls.Add(MyGridView);
          mynewform.RenderControl(htmlwriter);
          Response.Write(swriter.ToString());
          Response.End();
    }


C# Code : For GridView To Word

    protected void btn_word_Click(object sender, EventArgs e)
    {
          Response.AddHeader("content-disposition""attachment;filename=myreport.doc");
          Response.Cache.SetCacheability(HttpCacheability.NoCache);
          Response.ContentType = "application/vnd.word";
          System.IO.StringWriter swriter = new System.IO.StringWriter();
          System.Web.UI.HtmlTextWriter htmlwriter = new HtmlTextWriter(swriter);
 
          // Create a form to contain the gridview(MyGridView)
          HtmlForm mynewform = new HtmlForm();
          MyGridView.Parent.Controls.Add(mynewform);
          mynewform.Attributes["runat"] = "server";
          mynewform.Controls.Add(MyGridView);
          mynewform.RenderControl(htmlwriter);
          Response.Write(swriter.ToString());
          Response.End();
    }

create update delete xml in csharp asp.net


//How to create xml file using c#.net asp.net code
//Append Node/ Modify Node in XML using c#.net asp.net
//
using System.Xml;
using System.IO;
 protected void Button1_Click(object sender, EventArgs e)

{
  string filepath = MapPath("xml/XMLFile3.xml"); // path of xml where we want to save it
   create(filepath);
}

private void create(string filepath)    // filepath is path where we want to save xml file
{
   string xml = @"<?xml version='1.0' encoding='utf-8'?>
                    <ParentXMLNode>
                    <Header>
                           <xmlnode1>value1</xmlnode1>
                           <xmlnode2>value2</xmlnode2>
                    </Header>
                    <xmlnode3>value3</xmlnode3>
                    <xmlnode4>value4</xmlnode4>  
                    <Message>
                        <xmlnode5></xmlnode5>
                        <xmlnode5></xmlnode5>
                        <xmlnode6>
                               <Node1></Node1>
                        </xmlnode6>
                     </Message>
                    </ParentXMLNode>";

        XmlDocument docConfig = new XmlDocument();
        docConfig.LoadXml(xml);
        Literal1.Text = "<XMP>" + xml + "</XMP>";
        docConfig.Save(filepath);
    }

CountDown -Timer ajax control c#.net Asp.net

Task: CountDown Timer in ASP.NET using AjaxControl Toolkit

Description: Sometime we need to countdown timer on website as for bidding website or any else. Then we can use Ajax control to achieve this task. Here I created code for countdown timer (server time).
I used server countdown timer because for bidding we need server time not client machine time which used in javascript code.

note : need ajax control toolkit to add first.
It is freely available at http://www.asp.net/ajaxlibrary/AjaxControlToolkitSamlpleSite/
Here, you can find many sample code for how use ajax controls in your website.

In addition I make CSS for round corner of DIV tag. my div is as a circle.

////////////////
//Design Page ... Save it as timer.aspx
//////////////////


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="timer.aspx.cs" Inherits="timer" %>
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Untitled Page</title>
    <style type="text/css">
        .circle
        {
         text-align:center;
        float:left;
        width:60px;
        height:60px;
        background-color:#ffffff;
        border: 1px solid #000000;
        padding:20px 20px 20px 20px;
        -moz-border-radius: 50px;
        -webkit-border-radius: 50px;
        border-radius: 50px;
     
         font-family:Cambria;
         font-size:35px;
        }
        .styletable
        {
          font-family:Cambria;
            font-size:15px;
         font-weight:bold;
        }
     </style>
</head>
<body>
    <form id="countdowntimerform" runat="server">
    <div><br />
        <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
        </asp:ToolkitScriptManager>
        <br />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
         <asp:Timer ID="Timer1" runat="server" Interval="1000" ontick="Timer1_Tick">
        </asp:Timer>
        <br />
        <br />
        <table width="260">
        <tr>
         <td><div class="circle"><asp:Label ID="Label1" runat="server"></asp:Label></div></td>
         <td><div class="circle"><asp:Label ID="Label1" runat="server"></asp:Label></div></td>
         <td><div class="circle"><asp:Label ID="Label3" runat="server"></asp:Label></div></td>
         <td><div class="circle"><asp:Label ID="Label4" runat="server"></asp:Label></div></td>
        </tr>
        <tr align="center"><td><b>DAYS</b></td><td><b>HOURS</b></td><td><b>MIN</b></td><td><b>SEC</b></td></tr></table
        </ContentTemplate>
        </asp:UpdatePanel>
         </div>
    </form>
</body>
</html>



/////////////////////////////////////////////////////////////////////////////////////
Code Behind File    Save it as timer.aspx.cs
///////////////////////////////////////////////////////////////////////////////


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class timer : System.Web.UI.Page
{
    static DateTime setdt;
    protected void Page_Load(object sender, EventArgs e)
    {
     
    }
    protected void Timer1_Tick(object sender, EventArgs e)
    {
         DateTime dt = DateTime.Now;
         TimeSpan differ;
         System.DateTime date1 = new System.DateTime(2013, 4, 1, 20, 10, 0);
         differ = date1.Subtract(dt);
         double  t = differ.TotalSeconds;
       
           if (t>0)
           {
               double yr, mnth, dy, h, m, s;
               dy = differ.Days;
               h = differ.Hours;
               m = differ.Minutes;
               s = differ.Seconds;
               Label1.Text = dy.ToString();// +" Days " + h + " Hours " + m + " Minutes " + s + " Seconds left for celebration";
               Label2.Text = h.ToString();
               Label3.Text = m.ToString();
               Label4.Text = s.ToString();
           }
           else
           {
               Timer1.Enabled = false;
           }
    }
}
///////////////////////////////////////END OF C#.NET/ASP.NET CODE////////////////////////////////

Remove Html Tags from a String, C#.NET, ASP.NET


Task: Remove HTML tags from a string.

Description: When we update content using WYSIWYG HTML editor (ck-editor) then it used HTML tag for formatting the content. But some time we need the same content without any formatting so then we require the removing HTML tag from that content.

Here I use two variation for this first one is using a simple loop And Second one is using Regex.

// How convert a html tag to blank space in a string using c#.net/asp.net code
// Replacing the html tag <> to blank space, you can copy data with html tag and then convert to normal text
// eg. INPUT   -->  <div width="5">Hemant Singh <i>Rautela</i></div>
        OUTPUT--> Hemant Singh Rautela

//
//C#.NET , ASP.NET
// Method 1 : (Using Character Array)

 public string replace(string s)
 {
    int l = s.Length;
    int j = 0;
    char[] ch = s.ToCharArray();
    s = "";
    for (int i = 0; i < l; i++)
    {
        if (ch[i] == '<')
            j = 1;
        if (j == 1)
        {
            if (ch[i] == '>')
                j = 0;
            ch[i] = ' ';
        }
        s = s + ch[i].ToString();
    }
    return (s);
 }


// Method 2 (Using Regular Expressions- Regex)

 using System.Text.RegularExpressions;
 public string replace(string s)
 {
   String result = Regex.Replace(s, @"<[^>]*>", String.Empty);
 }