Remove Multiple Gridview Columns before Excel Export
-
Hello! I'm trying to find a code to delete multiple columns because when you delete a column the next column takes his place so for example: If you delete column 6 then column 7 becomes column six. I tried the following code with an for loop & a while loop: Dim field As DataControlField = gv.Columns(i) gv.Columns.Remove(field) & gv.columns.removeat(i) But same case that the column 7 becomes column 6 The variable removeColumns is an array with the column number that need to be deleted. If wanted I can also provide the Header Names Thanks a lot for anyone who can Help me!
Imports System.Data
Imports System.Configuration
Imports System.IO
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControlsPublic Class GridViewExportUtil
Public Shared Sub Export(ByVal fileName As String, ByVal gv As GridView, ByVal removeColumns As Integer())
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", fileName))
HttpContext.Current.Response.ContentType = "application/ms-excel"'Gridview column delete code should come here
Using sw As New StringWriter() Using htw As New HtmlTextWriter(sw) ' Create a form to contain the grid Dim table As New Table() ' add the header row to the table If gv.HeaderRow IsNot Nothing Then GridViewExportUtil.PrepareControlForExport(gv.HeaderRow) table.Rows.Add(gv.HeaderRow) End If ' add each of the data rows to the table For Each row As GridViewRow In gv.Rows GridViewExportUtil.PrepareControlForExport(row) table.Rows.Add(row) Next ' add the footer row to the table If gv.FooterRow IsNot Nothing Then GridViewExportUtil.PrepareControlForExport(gv.FooterRow) table.Rows.Add(gv.FooterRow) End If ' 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\]()