Prepare controls to remove while exporting GridView to Excel
In this artical i'm trying to explain remove controls while exporting gridview data to excel. Previously we did export data to excel or some other formats but here i'm trying to explain in Grid Header having controls means i want to remove all those controls while exporting and then export to excel.
Prepare Controls to remove while export GridView to Excel:
In this artical i'm trying to explain remove controls while exporting gridview data to excel. Previously we did export data to excel or some other formats but here i'm trying to explain in Grid Header having controls means i want to remove all those controls while exporting and then export to excel.
My GridView is look like thisGridView:
In my GridView Header i have some controls, while exporting with that controls i'm facing some what dificulties. So, before exporting i must delete those controls and then exported using the below code.Code Behind:
private static void RemoveControls(Control control)
{
for (int i = 0; i < control.Controls.Count; i++)
{
Control current = control.Controls[i];
if (current is DropDownList)
{
control.Controls.Remove(current);
}
else if (current is TextBox)
{
control.Controls.Remove(current);
}
else if (current is Button)
{
control.Controls.Remove(current);
}
else if (current is AjaxControlToolkit.TextBoxWatermarkExtender)
{
control.Controls.Remove(current);
}
else if (current is LinkButton)
{
control.Controls.Remove(current);
}
if (current.HasControls())
{
PrepareControlForExport(current);
}
}
}
public static void ExportToExcel(string fileName, GridView gv)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(
"content-disposition", string.Format("attachment; filename={0}.xls", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a form to contain the grid
System.Web.UI.WebControls.Table table = new System.Web.UI.WebControls.Table();
// add the header row to the table
if (gv.HeaderRow != null)
{
RemoveControls(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}
// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
RemoveControls(row);
table.Rows.Add(row);
}
// add the footer row to the table
if (gv.FooterRow != null)
{
RemoveControls(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();
}
}
}OutPut:
Using above code we remove controls in HeaderTemplate and export data to excel we fetch our desired out put using this.
You can also use given code snippet for controls to remove while exporting GridView to Excel