I have a gridview that needs to be exported to Excel. I have managed to remove the Checkboxes from Rows but don't know how to remove from the Header and also delete the Checkbox Column entirely. Thanks for help.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="Id">
<Columns>
<asp:TemplateField HeaderText="Select" >
<HeaderTemplate>
<input id="chkAll" onclick="checkAll(this);" runat="server" type="checkbox" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Event" HeaderText="Event" SortExpression="Event" />
<asp:BoundField DataField="Event_Description" HeaderText="Event_Description" SortExpression="Event_Description" />
<asp:BoundField DataField="Start_Date" HeaderText="Start_Date" SortExpression="Start_Date" />
</Columns>
</asp:GridView>
Here's the backend C# code to export to excel.
protected void download_Click(object sender, EventArgs e)
{
PrepareGridViewForExport(GridView1);
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=GridViewToExcel.xls");
Response.ContentType = "application/excel";
StringWriter sWriter = new StringWriter();
HtmlTextWriter hTextWriter = new HtmlTextWriter(sWriter);
GridView1.RenderControl(hTextWriter);
Response.Write(sWriter.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
private void PrepareGridViewForExport(Control gv)
{
Literal l = new Literal();
string name = String.Empty;
for (int i = 0; i < gv.Controls.Count; i++)
{
if (gv.Controls[i].GetType() == typeof(CheckBox))
{
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
if (gv.Controls[i].HasControls())
{
PrepareGridViewForExport(gv.Controls[i]);
}
}
}