Showing posts with label GridView. Show all posts
Showing posts with label GridView. Show all posts

Wednesday, January 5, 2011

Steps to generate an Excel file from a GridView

 

Assuming you have a databound GridView called GridView1 whose contents you want to export to an Excel file named “ExcelFile.xls” upon clicking a button with ID “ButtonExport”, there are two basic steps what you need to do.

Step 1: Add the code to the event handler for ButtonExport click event as follows:

protected void ButtonExport_Click(object sender, EventArgs e)
{
   Response.Clear();
   Response.Buffer = true;
   Response.AddHeader("content-disposition",
                      "attachment;filename=ExcelFile.xls");

   Response.Charset = "";
   Response.ContentType = "application/vnd.ms-excel";

   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();
} //end ButtonExport_Click

Step 2: Add the VerifyRenderingInServerForm method

You will need to add this method in order for the code in Step 1 to work.

public override void VerifyRenderingInServerForm(Control control)
{
       return;
}

Tuesday, December 21, 2010

Sorting a GridView

http://geekswithblogs.net/azamsharp/archive/2006/04/27/76612.aspx

This code from Azam Sharp works well ^_^


private const string ASCENDING = " ASC";
 
private const string DESCENDING = " DESC";
 public SortDirection GridViewSortDirection
    {
        
get
        
{
            
if (ViewState["sortDirection"] == null)
                ViewState["sortDirection"] = SortDirection.Ascending;

            
return (SortDirection) ViewState["sortDirection"];               
        }
        
set { ViewState["sortDirection"] = value; }
    }


    
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        
string sortExpression = e.SortExpression;

        
if (GridViewSortDirection == SortDirection.Ascending)
        {
            GridViewSortDirection = SortDirection.Descending;
            SortGridView(sortExpression, DESCENDING);
        }
        
else
        
{
            GridViewSortDirection = SortDirection.Ascending;
            SortGridView(sortExpression, ASCENDING);
        }  
      
    }

    
private void SortGridView(string sortExpression,string direction)
    {
        
//  You can cache the DataTable for improving performance
        
DataTable dt = GetData().Tables[0];

        DataView dv = 
new DataView(dt);
        dv.Sort = sortExpression + direction;        

        GridView1.DataSource = dv;
        GridView1.DataBind();        
    }