I have been browsing on web to find the exact solution. Unfortunately, lots of different suggestions which also not working, and finally I have found an article that’s very interesting.
One reason this error comes up is when the datagrid contains a server control, so you need to verify it before complaining.
There are 2 (maybe more) ways to solve this issue that I have proven and tested.
1. Disable features of the datagrid like sorting and remove unnecessary server controls.
2. If the above solution is not possible because you really need it. So, what you need to do is to clear the server controls on the fly, means you have to implement a sort of mechanism to work, but don’t worry about it there’s already a script that will help you to ease the work.
-
-
Public Sub ClearControls(ByVal control As Control)
-
'This function is used to Clear all the controls in the datagrid
-
'Will Clear all the ServerControls Which are in the Datagrid
-
'Such as edit command, paging, checkboxes in datagrid and all
-
'the server controls
-
'it will replace the server control with simple text for that control
-
'Where Can this be Used:
-
'Exporting Datagrid and Clearing Datagrid
-
Dim i As Integer
-
For i = control.Controls.Count - 1 To 0 Step -1
-
ClearControls(control.Controls(i))
-
Next i
-
-
If Not TypeOf control Is System.Web.UI.WebControls.TableCell Then
-
If Not (control.GetType().GetProperty("SelectedItem") Is Nothing) Then
-
Dim literal As New LiteralControl
-
control.Parent.Controls.Add(literal)
-
Try
-
literal.Text = CStr(control.GetType().GetProperty("SelectedItem").GetValue(control, Nothing))
-
Catch
-
End Try
-
control.Parent.Controls.Remove(control)
-
Else
-
If Not (control.GetType().GetProperty("Text") Is Nothing) Then
-
Dim literal As New LiteralControl
-
control.Parent.Controls.Add(literal)
-
literal.Text = CStr(control.GetType().GetProperty("Text").GetValue(control, Nothing))
-
control.Parent.Controls.Remove(control)
-
End If
-
End If
-
End If
-
Return
-
End Sub 'ClearControls
-
-
Protected Sub btnDownload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDownload.Click
-
Response.Clear()
-
Dim filename As String = "filename_" & Strings.Format(DateTime.Today, "MM-dd-yyyy") & ".xls"
-
-
Response.Clear()
-
Response.AddHeader("content-disposition", "attachment; filename=" & filename)
-
Response.Charset = ""
-
Response.ContentType = "application/vnd.xls"
-
Me.EnableViewState = False
-
Dim stringWrite As System.IO.StringWriter = New System.IO.StringWriter()
-
Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)
-
Response.Buffer = False
-
ClearControls(DataGrid1)
-
Me.DataGrid1.RenderControl(htmlWrite)
-
Response.Write(stringWrite.ToString())
-
'stringWrite.Dispose()
-
'htmlWrite.Dispose()
-
-
Response.End()
-
-
'Download()
-
-
End Sub