Wednesday, November 28, 2012

Creating multilingual websites

  • To create a multilingual application we need .resx (Resource) file.
  • The .resx file is an XML file, which contains Name and a value.
  • The value in the resource file is substituted at run-time.
  • The file name of the resource file should be name of the aspx file.
e.g. if our aspx file name is Test.aspx, then our resource file name should be Test.aspx.resx(Default resource file for the aspx file).
Test.aspx.en-US.resx (aspx file Name.Culture.resx)

To view the code inside the resx file, Right-click -> View Code

Home US

The data tag contains the string and the value.

To set the culture to the controls and to select the correct resource file we have to set the propertis Culture and UICulture

This two properties are available form the class System.Web.UI.Page

How to attach this value to the server controls?

Import the library
  • System.Threading
  • System.Globalization
There are two types of Asp.Net Folders
  • App_LocalResources
  • App_GlobalResources
App_LocalResources
Resource files for each aspx file
The resource file is embeded with the dll file.
App_GlobalResources
Global resource can be read from any page or code that is in the application.
If we are having some text, which is repeated in most of the pages, have the key and value.

Naming conversion for the resource file
<pagename>.aspx.<language>.resx

Type 1:LocalResources
Implicit coding for App_LocalResources

in the page directive add
Culture="auto:en-US" UICulture="auto"

meta:resourceKey="Label1"
in resx file, we have it as Label1.Text as the key name.

meta:resourceKey is called as ambient language

By default our default language is English
How change the language in Browser Settings
Internet Options -> Languages -> Add -> Chinese [Simplified]
Change the default order

If we are having a Label control, and how can we apply localization,
<asp:Label ID="Label1" runat="server" Text="Label" ForeColor="green"></asp:Label>
<asp:Label ID="Label1" runat="server" meta:resourceKey="Label1"></asp:Label>

In the resx file the name of each property is noted as ControlID.Property



Type 2:App_GlobalResources
App_GlobalResources

Select control -> Press F4 -> Expression -> Text -> Expression Type -> Resource -> ClassKey=Resource,

ResourceKey = We can do this only for the GlobalResources

Title="<%$ Resources:PageTitle %>"

Type 3:Dynamically change the language
Import the library
System.Threading
System.Globalization

Override the page method called InitializeCulture
This is the place where we have to set the culture.

protected override void InitializeCulture()
    {
        string language = Request.Form["ddlLanguage"];
        if (!String.IsNullOrEmpty(language))
        {
            Culture = UICulture = language;

            //For selecting the resource file for the languate
            Thread.CurrentThread.CurrentCulture = new CultureInfo(language);

            //For date and currencies
            //Language + Location => Locale
            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(language);

            WriteCookie("CultureInfo", language);
        }
        base.InitializeCulture();
    }


public void WriteCookie(string name, string value)
    {
        HttpContext.Current.Response.Cookies.Set(new HttpCookie(name, value));
    }

    public string ReadCookie(string name)
    {
        return Request.Cookies["CultureInfo"] != null ?
            Request.Cookies["CultureInfo"].Value : null;
    }

    //This is not needed, since it will be set in the InitializeCulture()
/*
    protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
    {
        WriteCookie("CultureInfo", ddlLanguage.SelectedValue);
    }
*/

To get the current culture
System.Globalization.CultureInfo currentCulture = 
System.Threading.Thread.CurrentThread.CurrentCulture;

To change the currency symbol
String.Format("{0:c}", 1000.2);

How to get the currency symbol according to the languagecode
Get Currency Symbol by Language-code

How to get the value from a resource file in code behind
private string GetMessage(string resourceKey)
    {
        return Convert.ToString(this.GetLocalResourceObject(resourceKey));
    }

How to get the value from a resource file in JavaScript
alert('<%= Convert.ToString(this.GetLocalResourceObject
("AlertLocationOrCustomer"))%>');

How to get the value from a resource file in DropDownList/ListBox asp:ListItem
-Select-

Error

//If no any resource file available
Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "Test.aspx.resources" was correctly embedded or linked into assembly "App_LocalResources.root.uhdc5eth" at compile time, or that all the satellite assemblies required are loadable and fully signed.

Title="<%$ Resources:PageTitle %>"
Error parsing attribute 'title': The resource object with key 'PageTitle' was not found.
  • If there is no default resx file.
  • If there is no resx file for the aspx file.
  • If the aspx file in a sub-folder then we have to create a App_LocalResources in side the sub-folder and create the resx file.

How do I localize the column headers in a gridview?
Curtesy
In your bound field add resource key like this:
In your resource file you need to add a key with name

Product.HeaderText and in Value = ????
Similarly you can do the same for footer

Product.FooterText and in Value = ????

How to localize in external javascript file
In the master page add the hidden control.

In the code behind of the master page set the current langauge.
hdnLang.Value = SessionProxy.Search.Language.ToLower();
eg: for, how to localize in external javascript file?
var locale = ($('#ctl00_hdnLang').val() || "en-us");
var show = { "zh-cn": "顯示", "en-us": "Show" };
var hide = { "zh-cn": "隱藏", "en-us": "Hide" };

$('img.image-selector').toggle(
    function () {
        $(this).attr('src', '../images/Show.JPG');
        $(this).attr('title', show[locale]);
    },
    function () {
        $(this).attr('src', '../images/Hide.JPG');
        $(this).attr('title', hide[locale]);
    }
);
Understanding Globalization and Localization in .NET
Using Resources for Localization with ASP.NET
Extending the ASP.NET 2.0 Resource-Provider Model

Asp.net 3.5 Application Architecture and Design- Chapter 9 Localization

Get Currency Symbol by LanguageCode

Friday, November 9, 2012

Setting minDate and maxDate for jquery datepicker

$(function () {
    var dateToday = new Date();
    var startDate = new Date(dateToday.getFullYear(), 
                 dateToday.getMonth(), dateToday.getDate() - 30);
    $("#txtFromDate").datepicker({
        minDate: startDate,
        maxDate: dateToday
    });
    $("#txtToDate").datepicker({
        minDate: startDate,
        maxDate: dateToday
    });
});

Tuesday, September 25, 2012

Various where types

DECLARE @TEMP TABLE
                    (
                                        Name VARCHAR(50),
                                        Sex  CHAR(1)    ,
                                        Age  INT
                    )

INSERT INTO @Temp
SELECT 'Babu', 'M', 31 UNION ALL
SELECT 'Krishna', 'M', 31 UNION ALL
SELECT 'Kanagu', 'M', 31 UNION ALL
SELECT 'rathinam', 'M', 31 UNION ALL
SELECT 'Kumarasamy', 'M', 31 UNION ALL
SELECT 'Suseela', 'F', 31 UNION ALL
SELECT 'Venkatesh', 'M', 31

DECLARE @Name VARCHAR(50),
        @Sex  CHAR(1),
        @Age  INT,
        @Type VARCHAR(50)

Using boolean logic
SELECT * FROM @Temp
WHERE 1 = 1
AND (@Name IS NULL OR Name = @Name)
AND (@Sex IS NULL OR Sex = @Sex)
AND (@Age IS NULL OR Age = @Age)

SET @Name = 'BABU'

SELECT * FROM @Temp
WHERE 1 = 1
AND (@Name IS NULL OR Name = @Name)
AND (@Sex IS NULL OR Sex = @Sex)
AND (@Age IS NULL OR Age = @Age)

SET @Name = 'BABU'
SET @Sex = 'BABU'

SELECT * FROM @Temp
WHERE 1 = 1
AND (@Name IS NULL OR Name = @Name)
AND (@Sex IS NULL OR Sex = @Sex)
AND (@Age IS NULL OR Age = @Age)

Using boolean logic
SET @Type = 'NAME'

SELECT * FROM @Temp
WHERE (@Type = 'NAME' AND Name = @Name)
OR (@Type = 'SEX' AND Sex = @Sex)
OR (@Type = 'AGE' AND Age = @Age)

Using the Case expression
SET @Name = NULL
SET @Sex = NULL
SET @Age = NULL
SELECT * FROM @Temp
WHERE 1 = 1
AND Name = CASE WHEN @Name IS NOT NULL THEN @Name ELSE Name END
AND Sex = CASE WHEN @Sex IS NOT NULL THEN @Sex ELSE Sex END
AND Age = CASE WHEN @Age IS NOT NULL THEN @Age ELSE Age END

SET @Name = 'BABU'
SET @Sex = 'M'
SET @Age = NULL
SELECT * FROM @Temp
WHERE 1 = 1
AND Name = CASE WHEN @Name IS NOT NULL THEN @Name ELSE Name END
AND Sex = CASE WHEN @Sex IS NOT NULL THEN @Sex ELSE Sex END
AND Age = CASE WHEN @Age IS NOT NULL THEN @Age ELSE Age END

SET @Name = 'BABU'
SET @Sex = 'BABU'
SET @Age = NULL
SELECT * FROM @Temp
WHERE 1 = 1
AND Name = CASE WHEN @Name IS NOT NULL THEN @Name ELSE Name END
AND Sex = CASE WHEN @Sex IS NOT NULL THEN @Sex ELSE Sex END
AND Age = CASE WHEN @Age IS NOT NULL THEN @Age ELSE Age END

Using the ISNULL and NULLIF
SET @Name = NULL
SET @Sex = NULL
SET @Age = NULL
SELECT * FROM @Temp
WHERE 1 = 1
AND Name = ISNULL(NULLIF(@Name, NULL), Name)
AND Sex = ISNULL(NULLIF(@Sex, NULL), Sex)
AND Age = ISNULL(NULLIF(@Age, NULL), Age)

SET @Name = 'BABU'
SET @Sex = 'M'
SET @Age = NULL
SELECT * FROM @Temp
WHERE 1 = 1
AND Name = ISNULL(NULLIF(@Name, NULL), Name)
AND Sex = ISNULL(NULLIF(@Sex, NULL), Sex)
AND Age = ISNULL(NULLIF(@Age, NULL), Age)

SET @Name = 'BABU'
SET @Sex = 'BABU'
SET @Age = NULL
SELECT * FROM @Temp
WHERE 1 = 1
AND Name = ISNULL(NULLIF(@Name, NULL), Name)
AND Sex = ISNULL(NULLIF(@Sex, NULL), Sex)
AND Age = ISNULL(NULLIF(@Age, NULL), Age)

Execution plans


Monday, September 24, 2012

Get Currency Symbol by LanguageCode

Tutorial on using CultureInfo and RegionInfo

Creating multilingual websites

Code to set the culture and get the currency symbol for that culture.
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 System.Threading;
using System.Globalization;

/// 
/// Set the culture and get the currency symbol
/// 
public sealed class MyCulture
{
    public MyCulture()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public void SetCulture(string CultureCode)
    {
        Thread.CurrentThread.CurrentCulture = 
            CultureInfo.CreateSpecificCulture(CultureCode);

        Thread.CurrentThread.CurrentUICulture = 
            new CultureInfo(CultureCode);
    }

    public string GetCurrencySymbol(string CultureCode)
    {
        SetCulture(CultureCode);

        CultureInfo UsersCulture = Thread.CurrentThread.CurrentCulture;
        RegionInfo myRegion = new RegionInfo(UsersCulture.LCID);

        return myRegion.CurrencySymbol;
    }
}
How to pass the input?
MyCulture obj = new MyCulture();
String symbol = obj.GetCurrencySymbol("ta-IN");

When we are passing the input culture is necessary.
i.e. we have to pass "ta-IN" or "ta" but not "IN".


List of CultureCodes
How to add currency symbol in the gridview?
We can do it both from the server side or from the client side.
//Setting currency symbol from the service side
        protected void grdWithCurrencySign_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header)
            {
                MyCulture obj = new MyCulture();
                string symbol = obj.GetCurrencySymbol("ta-in");

                e.Row.Cells[1].Text = symbol + " " + e.Row.Cells[1].Text;
            }
        }

        public string AddCurrency(string amount)
        {
            MyCulture obj = new MyCulture();
            return amount + " " + obj.GetCurrencySymbol("ta-in");
        }

                
                    
                    
                    
                        
                            <%# AddCurrency(Convert.ToString(Eval("Salary")))%>
                        
                    
                
            

Friday, September 21, 2012

GROUP BY and DISTINCT

DECLARE @Team TABLE(EventDate DATETIME, Seconds BIGINT)

INSERT INTO @Team
SELECT '2012-08-25',440 UNION ALL
SELECT '2012-08-25',1232 UNION ALL
SELECT '2012-08-25',1232 UNION ALL
SELECT '2012-08-25',1232 UNION ALL
SELECT '2012-08-25',1232 UNION ALL
SELECT '2012-08-25',1232 UNION ALL
SELECT '2012-08-25',1232 UNION ALL
SELECT '2012-08-25',7740 UNION ALL
SELECT '2012-08-25',18640 UNION ALL
SELECT '2012-08-25',18640 UNION ALL
SELECT '2012-08-25',18640 UNION ALL
SELECT '2012-08-25',512 UNION ALL
SELECT '2012-08-25',512 UNION ALL
SELECT '2012-08-25',512 UNION ALL
SELECT '2012-08-25',512 UNION ALL
SELECT '2012-08-25',512 UNION ALL
SELECT '2012-08-25',512

SELECT EventDate, Seconds FROM @Team

Sum the column Seconds for the group EventDate
SELECT EventDate, SUM(Seconds) Seconds
FROM @Team
GROUP BY EventDate
The value in the column Seconds is summed with the duplicate value.


How to sum the column without duplicate
SELECT EventDate, Sum(DISTINCT Seconds) Seconds 
FROM     @Team 
GROUP BY EventDate

SELECT   EventDate, Sum(Seconds) AS Seconds 
FROM     ( SELECT EventDate, Seconds 
                  FROM @Team 
                  GROUP BY EventDate, Seconds ) AS T 
GROUP BY EventDate

SELECT   EventDate, Sum(Seconds) AS Seconds 
FROM     ( SELECT DISTINCT EventDate, Seconds 
           FROM @Team ) AS T 
GROUP BY EventDate

Thursday, August 30, 2012

Get only business days in a month in SQL SERVER

DECLARE @Start_Date DATETIME
SET @Start_Date = GETDATE()
SET @Start_Date = CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(@Start_Date)-1),@Start_Date),101)

DECLARE @Holiday TABLE(HoliDay DATETIME)

INSERT INTO @Holiday(HoliDay) VALUES('2012-08-15')
 
;WITH MonthDays(day_num, calendar_dt) AS
     ( SELECT 1                                        AS day_num,
             DATEADD(d, -DAY(@Start_Date)+1, @Start_Date ) AS calendar_dt
     
     UNION ALL
     
     SELECT day_num + 1,
            DATEADD(d, 1, calendar_dt)
     FROM   MonthDays
     WHERE  MONTH(DATEADD(d, 1, calendar_dt)) = MONTH(@Start_Date)
     )
--SELECT * FROM MonthDays 

/*
SELECT *, datename(dw, calendar_dt), (DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH, 0, calendar_dt), 0), calendar_dt) +1) as [Week]
FROM MonthDays
WHERE ((DATEPART(dw, calendar_dt) + @@DATEFIRST) % 7) NOT IN (1)
-- 0 for saturday, 1 for sunday

--WHERE ((DATEPART(dw, calendar_dt) + @@DATEFIRST) % 7) NOT IN (0, 1)
--http://msdn.microsoft.com/en-us/library/ms174420(v=sql.90).aspx
*/

SELECT day_num    ,
       calendar_dt,
       WeekDayName,
       [Week]
FROM  ( SELECT day_num                                 ,
               calendar_dt                             ,
               DATENAME(dw, calendar_dt)                                                            AS WeekDayName,
               (DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH, 0, calendar_dt), 0), calendar_dt) +1) AS [Week]
       FROM    MonthDays
       WHERE   ((DATEPART(dw, calendar_dt) + @@DATEFIRST) % 7 ) NOT IN (1)
       ) AS T
WHERE  ( WeekDayName != 'Saturday' 
   OR     [Week] NOT IN (1, 3, 5)
       )
       --To remove the holiday
AND    day_num NOT IN
       (SELECT DATEPART(DD, HoliDay)
       FROM    @Holiday
       )

Thursday, July 26, 2012

Get only single record from a group with various conditons

  • If an employee has both eligible and not eligible get the eligible record with min of Cal.
  • If an employee has only eligible or not eligible get the record with min of Cal.
  • For the above both conditions, we should get only one record for each employee.

DECLARE @Temp TABLE(EmpID VARCHAR(50), ISEligible CHAR(1), Cal INT)
        
        INSERT INTO @Temp(EmpID, ISEligible, Cal)
        SELECT '8829', 'Y', 10   UNION ALL
        SELECT '8829', 'N', 3    UNION ALL
        SELECT '8829', 'Y', 8    UNION ALL
        SELECT '1256', 'Y', 0    UNION ALL
        SELECT '1256', 'N', NULL UNION ALL
        SELECT '1111', 'N', NULL UNION ALL
        SELECT '1111', 'N', NULL UNION ALL
        SELECT '2222', 'Y', NULL UNION ALL
        SELECT '2222', 'Y', NULL
        
        SELECT * FROM @Temp
        
        SELECT *
        FROM  ( SELECT  ROW_NUMBER() OVER(PARTITION BY EmpID 
                   ORDER BY ISEligible DESC, Cal asc) RowNum,
                        EmpID     ,
                        ISEligible,
                        Cal
               FROM    @Temp
               )
               AS Temp
       WHERE  RowNum = 1

Wednesday, July 25, 2012

Creating custom sort rules for SQL Server

-- Create a Location table 
DECLARE @LOCATION TABLE 
  ( 
     ID           INT IDENTITY(1, 1), 
     LocationName VARCHAR(50) 
  ) 

-- Insert dummy data 
INSERT INTO @Location
SELECT 'Chitoor'  UNION 
SELECT 'Idappadi'  UNION 
SELECT 'Salem'   UNION 
SELECT 'Savadipalayam' UNION 
SELECT 'Sankri'   UNION 
SELECT 'Morasapatti' UNION 
SELECT 'Polampatti' 

-- SELECT with plain our custom sort rules 
SELECT * 
FROM   @Location 
ORDER  BY CASE LocationName 
            WHEN 'Salem' THEN 1 
            WHEN 'Idappadi' THEN 2 
            WHEN 'Chitoor' THEN 3 
            WHEN 'Savadipalayam' THEN 4 
            ELSE 5000 
          END 
The column value which have the sort order, will order by the sort value in ascending.
If the column value which didn't have no sort order will order first Try checking by removing the else part.
If we want to use like clause in the ORDER BY statement, then how?
Move the sort columnName from case to when
SELECT * 
FROM   @Location 
ORDER  BY CASE  
            WHEN LocationName = 'Salem' THEN 1 
            WHEN LocationName = 'Idappadi' THEN 2 
            WHEN LocationName LIKE '%C%' THEN 3 
            WHEN LocationName =  'Savadipalayam' THEN 4 
            ELSE 5000 
          END 

Thursday, July 5, 2012

ISNULL + NULLIF instead of CASE WHEN

Difference between NULL and (Empty or ' ')
ISNULL() vs COALESCE()

ISNULL ( <check_expression>, <replacement_value>)
Replaces check_expression with the specified replacement_value, when check_expression is null

NULLIF(<expression>, <expression>)
  • Returns a null value if the two specified expressions are equal.
  • Returns the first expression if the two expressions are not equal.
  • ReturnType is the type of the first expression
  • The type of the first argument to NULLIF cannot be the NULL constant because the type of the first argument has to be known.

DECLARE @EmpID VARCHAR(50)
SELECT
       CASE
              WHEN @EmpID IS NULL
              THEN 'rkbabu'
              ELSE @EmpID
       END

SELECT ISNULL(NULLIF(@EmpID, NULL), 'rkbabu')

SELECT NULLIF(10,20) ------> 10
SELECT NULLIF(10, NULL) ------> 10
SELECT NULLIF(10, 10) -------> NULL
SELECT NULLIF('', '     ') ----------> NULL 
SELECT NULLIF('@', '@@') ------> @

SELECT NULLIF(NULL, 10) ------> ERROR -> None of the result expressions in a CASE specification can be NULL.
SELECT NULLIF(NULL, NULL) ------> ERROR -> None of the result expressions in a CASE specification can be NULL.

DECLARE @EmpID VARCHAR(50)
SELECT NULLIF(@EmpID, 10) ----------> NULL
SELECT NULLIF(@EmpID, @EmpID) ----------> NULL

SELECT CASE WHEN NULL = 10 THEN NULL ELSE 10 END ------> 10
SELECT CASE WHEN 10 = NULL THEN NULL ELSE 10 END ------> 10
SELECT CASE WHEN NULL = NULL THEN NULL ELSE 10 END ------> 10 Since one null not equal to another null

Consider some time we will use case in the where condition, this can be replaced with
ISNULL and NULLIF function
DECLARE @Column1 INT, @Column2 INT

SET @Column1 = -1;

SELECT *
FROM tableName
WHERE Column1 = CASE WHEN @Column1 = -1 THEN Column1  ELSE @Column1 END
AND Column2 = CASE WHEN @Column2 IS NOT NULL THEN @Column2 ELSE Column2 END

SELECT *
FROM tableName
WHERE Column1 = ISNULL(NULLIF(@Column1, -1), Column1)
AND Column2 = ISNULL(NULLIF(@Column2, NULL), Column2)

Tuesday, June 19, 2012

Animated Flash chart

  • http://www.fusioncharts.com/goodies/fusioncharts-free/
  • Follow the steps
    • It will download a file FusionChartsFree.zip
  • After extraction go to the path
    • FusionChartsFree\FusionChartsFree\Code\CSNET
  • Copy the folder FusionCharts to your root directory which contains .swf files
    • FusionChartsFree\FusionChartsFree\Code\CSNET\FusionCharts
  • Copy FusionCharts.cs to your App_Config from the path
    • FusionChartsFree\FusionChartsFree\Code\CSNET\App_Code
  • Create a literal control in your aspx page
    • <asp:Literal ID="FCLiteral" runat="server"></asp:Literal>
  • In the code behind, ddd the namespaces
    • using InfoSoftGlobal;
    • using System.Drawing;
private void LoadFusionChart(DataTable dt)
    {
        string strXML;
        //http://www.codeweblog.com/2010-03-10-4-fusioncharts-of-the-xml-tag-attributes/
        //https://www.ourrelationship.com/mod/mcfeedback/Fusion/Contents/ChartSS/XML_MSLine2D.html
        //http://forum.fusioncharts.com/topic/2018-bug-duplicate-y-axis-labels-with-decimalprecision0/

        //Generate the graph element
        strXML = "";
        //showPercentageValues='0' showLegend='0' rotateValues='1' showDivLineValue='1'

        Random randonGen = new Random();

        int width = 100;

        foreach (DataRow dr in dt.Rows)
        {
            Color randomColorName = Color.FromArgb(randonGen.Next(255), 
                randonGen.Next(255), randonGen.Next(255));
            String randomColor = ColorTranslator.ToHtml(randomColorName);

            strXML += "";
            strXML += "";

            width += 50;
        }

        //Finally, close  element
        strXML += "";

        //We should be careful about the swf file path
        FCLiteral.Text = FusionCharts.RenderChartHTML("../FusionCharts/FCF_Column3D.swf", "", strXML, 
            "myFirst", width.ToString(), "400", false); ;
    }

Wednesday, April 25, 2012

Debugging Windows Service

Select the service name
Press the button Attach
Have a break point in your code to debug.

Thursday, January 19, 2012

Exporting gridview to excel with multiple headers

In the code behind declare GridViewRow globally for the page.
Refer the link merging-gridview-with-multiple-headers
Add the ImageButton in the aspx page.

<asp:ImageButton ToolTip="Csv" ID="btnCsvDown" runat="server" ImageUrl="~/Images/csv.jpg" OnClick="ibtnDownload_Click" CommandName="Csv"/>

<asp:ImageButton ToolTip="Word" ID="btnWordDown" runat="server" ImageUrl="~/Images/word-icon.png" OnClick="ibtnDownload_Click" CommandName="Word" />

<asp:ImageButton ToolTip="Excel" ID="btnExcelDown" runat="server" ImageUrl="~/Images/excel-icon.png" OnClick="ibtnDownload_Click" CommandName="Excel"/>

<asp:ImageButton ToolTip="Pdf" ID="btnPdfDown" runat="server" ImageUrl="~/Images/pdf-icon.png" OnClick="ibtnDownload_Click" CommandName="Pdf"/>

Click events for all the download Image buttons.
protected void ibtnDownload_Click(object sender, ImageClickEventArgs e)
    {
        ImageButton imgButton = sender as ImageButton;
        GridViewExportUtil.Export("Report.xls", this.gvStylish, HeaderRow,
            DateTime.Now.AddDays(-20).ToShortDateString(),
            DateTime.Now.ToShortDateString(), imgButton.CommandName.ToUpper());
    }
The below source code is developed by Mattberseth.
I have updated this, when we are exporting a gridview with multiple headers. mattberseth
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public class GridViewMultipleHeadersExportUtil
{
    public static void Export(string fileName, GridView gv)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
        HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "utf-8");
        HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
        HttpContext.Current.Response.AddHeader("oCodepage", "65001");

        HttpContext.Current.Response.Charset = "utf-8";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1253");

        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {
                //  Create a table to contain the grid
                Table table = new Table();

                //  include the gridline settings
                table.GridLines = gv.GridLines;

                table.Rows.Add(CreateTableRow("Report Generated on: " +
                 DateTime.Now.ToString("MM/dd/yyyy"), 5));

                //  add the header row to the table
                if (gv.HeaderRow != null)
                {
                    GridViewMultipleHeadersExportUtil.PrepareControlForExport(gv.HeaderRow);

                    foreach(TableCell tcHeader in gv.HeaderRow.Cells )  
                        tcHeader.BackColor = System.Drawing.Color.LightGray;  
                    //gv.HeaderRow.BackColor = System.Drawing.Color.LightGray; 
                    table.Rows.Add(gv.HeaderRow);
                }

                //  add each of the data rows to the table
                foreach (GridViewRow row in gv.Rows)
                {
                    //Set the default color  
                    System.Drawing.Color color = row.BackColor;
                    if (color != System.Drawing.Color.White)
                    {
                        row.BackColor = System.Drawing.Color.White;
                        foreach (TableCell tcRow in row.Cells)
                            tcRow.BackColor = color;
                    }

                    GridViewMultipleHeadersExportUtil.PrepareControlForExport(row);
                    table.Rows.Add(row);
                }

                //  add the footer row to the table
                //   if (gv.FooterRow != null)
                //   {
                //       GridViewMultipleHeadersExportUtil.PrepareControlForExport(gv.FooterRow);
                //       table.Rows.Add(gv.FooterRow);
                //   }

                //  render the table into the htmlwriter
                table.RenderControl(htw);

                //render the htmlwriter into the response

                String s = sw.ToString();

                HttpContext.Current.Response.Write(s);
                HttpContext.Current.Response.End();
            }
        }
    }


    public static void Export(string fileName, GridView gv, GridViewRow HeaderRow, 
                              string fdate, string tdate, string strExportType)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);

        switch (strExportType)
        {
            case "WORD":
                HttpContext.Current.Response.ContentType = "application/ms-word";
                fileName = fileName.Replace(Path.GetExtension(fileName), ".doc");
                break;
            case "EXCEL":
                HttpContext.Current.Response.ContentType = "application/ms-excel";
                fileName = fileName.Replace(Path.GetExtension(fileName), ".xls");
                break;
            case "PDF":
                HttpContext.Current.Response.ContentType = "application/pdf";
                fileName = fileName.Replace(Path.GetExtension(fileName), ".pdf");
                break;
            case "CSV":
                HttpContext.Current.Response.ContentType = "application/text";
                fileName = fileName.Replace(Path.GetExtension(fileName), ".csv");
                break;
        }

        HttpContext.Current.Response.AddHeader(
    "content-disposition", string.Format("attachment; filename={0}", fileName));

        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {
                //  Create a table to contain the grid
                Table table = new Table();

                //  include the gridline settings
                table.GridLines = gv.GridLines;

                table.Rows.Add(CreateTableRow("Report from " + fdate + " to " + tdate, 5));
                table.Rows.Add(CreateTableRow("Report Generated on: " +
                 DateTime.Now.ToString("MM/dd/yyyy"), 5));

                //  add the new header row to the table
                if (HeaderRow != null)
                {
                    PrepareControlForExport(HeaderRow);

                    //This set entire excel row as LightGray
                    //HeaderRow.BackColor = System.Drawing.Color.LightGray;

                    //This set only columns we are exporting
                    foreach (TableCell tcHeader in HeaderRow.Cells)
                        tcHeader.BackColor = System.Drawing.Color.LightGray;

                    table.Rows.Add(HeaderRow);
                }

                //  add the header row to the table
                if (gv.HeaderRow != null)
                {
                    //Since we are merging the header cell. We have to remove the cell which are not needed
                    /**/
                    GridViewRow gridViewHeader = gv.HeaderRow;
                    for (int removeCell = 2; removeCell >= 0; removeCell--)
                        gridViewHeader.Cells.RemoveAt(removeCell);
                    
                    //This set only columns we are exporting
                    foreach (TableCell tcHeader in gridViewHeader.Cells)
                        tcHeader.BackColor = System.Drawing.Color.LightGray;
                    //gridViewHeader.BackColor = System.Drawing.Color.LightGray;
                    /**/

                    //GridViGridViewMultipleHeadersExportUtilewExportUtil.PrepareControlForExport(gv.HeaderRow);
                    //table.Rows.Add(gv.HeaderRow);
                    GridViewMultipleHeadersExportUtil.PrepareControlForExport(gridViewHeader);
                    table.Rows.Add(gridViewHeader);
                }

                //  add each of the data rows to the table
                foreach (GridViewRow row in gv.Rows)
                {
                    GridViewMultipleHeadersExportUtil.PrepareControlForExport(row);

                    /**/
                    //Set the default color
                    System.Drawing.Color color = row.BackColor;

                    //Set the entire excel row as white
                    if (color != System.Drawing.Color.White)
                        row.BackColor = System.Drawing.Color.White;

                    if (row.Cells[0].Text.ToUpper().Contains("TOTAL") ||
                        row.Cells[0].Text.ToUpper().Contains("GRAND"))
                    {
                        color = System.Drawing.Color.LightGray;
                        row.Font.Bold = true;
                    }

                    //Set the color only for the Total and Grand rows
                    if (color != System.Drawing.Color.White)
                        foreach (TableCell tcRow in row.Cells)
                            tcRow.BackColor = color;
                    /**/

                    table.Rows.Add(row);
                }

                //  add the footer row to the table
                if (gv.FooterRow != null)
                {
                    GridViewMultipleHeadersExportUtil.PrepareControlForExport(gv.FooterRow);
                    table.Rows.Add(gv.FooterRow);
                }

                //  render the table into the htmlwriter
                table.RenderControl(htw);

                //  render the htmlwriter into the response
                HttpContext.Current.Response.Write(sw.ToString());
                HttpContext.Current.Response.End();
            }
        }
    }
    /*
    private static void ExportToPdf()
    {
        // Create instance of a new document
        Document doc = new Document(PageSize.A4, 10, 10, 50, 50);
        // Change   the content type to application/pdf !Important
        HttpContext.Current.Response.ContentType = "application/pdf";
        // Get   Instance of pdfWriter to be able to create 
        // the document in the OutputStream
        PdfWriter.GetInstance(doc, HttpContext.Current.Response.OutputStream);
        // Create   Style Sheet
        StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();
        //--styles.LoadTagStyle("ol", "leading", "16,0");
        doc.Add(new Header(iTextSharp.text.html.Markup.HTML_ATTR_STYLESHEET, "Style.css"));
        // Open the   document to be able to write to it
        doc.Open();
        //--styles.LoadTagStyle("li", "face", "garamond");
        //--styles.LoadTagStyle("span", "size", "8px");
        //--styles.LoadTagStyle("body", "font-family", "times new roman");
        //--styles.LoadTagStyle("body", "font-size", "10px");
        // Parse   html to PDF understandable objects
        var objects = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new StreamReader(Server.MapPath("Order.aspx"), Encoding.Default), styles);
        for (int k = 0; k < objects.Count; k++)
        {
            doc.Add((IElement)objects[k]);
        }
        // Close   the document, rendering it to the browser
        doc.Close();
    }
     */
   
    /// Replace any of the contained controls with literals
    private static void PrepareControlForExport(Control control)
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
            //ctl.GetType().FullName == "System.Web.UI.WebControls.DataControlLinkButton")
            Control current = control.Controls[i];
            switch (current.GetType().Name)
            {
                case "LinkButton":
                    //ReplaceControl(control, i, (current as LinkButton).Text);
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
                    break;
                case "ImageButton":
                    //ReplaceControl(control, i, (current as ImageButton).AlternateText);
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
                    break;
                case "HyperLink":
                    //ReplaceControl(control, i, (current as HyperLink).Text);
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
                    break;
                case "DropDownList":
                    //ReplaceControl(control, i, (current as DropDownList).SelectedItem.Text);
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
                    break;
                case "CheckBox":
                    //ReplaceControl(control, i, (current as CheckBox).Checked ? "True" : "False");
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
                    break;
            }
           
            if (current.HasControls())
            {
                GridViewMultipleHeadersExportUtil.PrepareControlForExport(current);
            }
        }
    }

    //private static void ReplaceControl(Control control, int i, string text)
    //{
    //    control.Controls.Remove(text);
    //    control.Controls.AddAt(i, new LiteralControl(text));
    //}

    public static TableRow CreateTableRow(string text, int iColSpan)
    {
        TableRow objTableRow = new TableRow();
        TableCell tc = new TableCell();
        tc.Text = text;
        tc.HorizontalAlign = HorizontalAlign.Left;
        tc.Font.Bold = true;
        tc.ColumnSpan = iColSpan;
        objTableRow.Cells.Add(tc);
        return objTableRow;
   }
}
Export GridView with Images to Word Excel and PDF Formats in ASP.Net Soure Code References