Hisham Aburass
Hisham Aburass

Reputation: 625

How can I use Display Name attribute with GridView when exporting to Excel?

I want to set the Column header text with [DisplayName()] attribute when I export the List to Excel file. any solution ?

GridView gv = new GridView();
gv.DataSource = ExportList;

gv.DataBind();

 System.Web.HttpContext.Current.Response.ClearContent();
 System.Web.HttpContext.Current.Response.Buffer = true;
 System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=Rapor.xls");
 System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel";
 System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Unicode;
 System.Web.HttpContext.Current.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
System.Web.HttpContext.Current.Response.Output.Write(sw.ToString());
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.End();

Upvotes: 3

Views: 1070

Answers (1)

Iman Hamidi
Iman Hamidi

Reputation: 198

You must use RowDataBound event of grid like this: First put this line after creating gv:

gv.RowDataBound+=GvOnRowDataBound;

Then follow this code:

private void GvOnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        for (int i = 0; i < e.Row.Cells.Count;i++)
        {
            var customAttributes =
                typeof (YourClass).GetProperty(e.Row.Cells[i].Text).CustomAttributes.ToList();
            var displayNameAttribute =
                customAttributes.FirstOrDefault(
                    aa => aa.AttributeType.FullName.Equals("System.ComponentModel.DisplayNameAttribute"));
            if (displayNameAttribute != null)
                e.Row.Cells[i].Text = displayNameAttribute.ConstructorArguments[0].ToString();
        }
    }
}

Remember change YourClass to the name of your class.

Upvotes: 6

Related Questions