Hello, I have the following code, I put this into App_code.
public static void PrepareGridViewForExport(C
ontrol gv)
{
LinkButton lb = new LinkButton();
Literal l = new Literal();
string name = String.Empty;
for (int i = 0; i < gv.Controls.Count; i++) {
if (gv.Controls[i].GetType() == typeof(LinkButton))
{
l.Text = (gv.Controls[i] as LinkButton).Text;
gv.Controls.Remove(gv.Cont
rols[i]);
gv.Controls.AddAt(i, l);
}
else if (gv.Controls[i].GetType() == typeof(DropDownList))
{
l.Text = (gv.Controls[i] as DropDownList).SelectedItem
.Text;
gv.Controls.Remove(gv.Cont
rols[i]);
gv.Controls.AddAt(i, l);
}
else if (gv.Controls[i].GetType() == typeof(CheckBox))
{
l.Text = (gv.Controls[i] as CheckBox).Checked ? "True" : "False";
gv.Controls.Remove(gv.Cont
rols[i]);
gv.Controls.AddAt(i, l);
}
if (gv.Controls[i].HasControl
s())
{
PrepareGridViewForExport(g
v.Controls
[i]);
}
}
}
public static void ExportGridView(GridView g1)
{
string attachment = "attachment; filename=Attachment.xls";
HttpContext.Current.Respon
se.ClearCo
ntent();
HttpContext.Current.Respon
se.AddHead
er("conten
t-disposit
ion", attachment);
HttpContext.Current.Respon
se.Content
Type = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
g1.RenderControl(htw);
HttpContext.Current.Respon
se.Write(s
w.ToString
());
HttpContext.Current.Respon
se.End();
}
But I got this error
System.Web.HttpException was unhandled by user code
Message="Control 'ctl00_ContentPlaceHolder1
_GridView1
' of type 'GridView' must be placed inside a form tag with runat=server."
Source="System.Web"
ErrorCode=-2147467259
StackTrace:
at System.Web.UI.Page.VerifyR
enderingIn
ServerForm
(Control control)
at System.Web.UI.WebControls.
GridView.R
ender(Html
TextWriter
writer, Boolean renderPanel)
at System.Web.UI.WebControls.
GridView.R
ender(Html
TextWriter
writer)
at System.Web.UI.Control.Rend
erControlI
nternal(Ht
mlTextWrit
er writer, ControlAdapter adapter)
at System.Web.UI.Control.Rend
erControl(
HtmlTextWr
iter writer, ControlAdapter adapter)
at System.Web.UI.Control.Rend
erControl(
HtmlTextWr
iter writer)
at ExcelHelper.ExportGridView
(GridView g1) in c:\Inetpub\wwwroot\WebSite
\App_Code\
ExcelHelpe
r.cs:line 67
at ListDetails.Button3_Click(
Object sender, EventArgs e) in c:\Inetpub\wwwroot\WebSite
\DynamicDa
ta\CustomP
ages\Citie
s\ListDeta
ils.aspx.c
s:line 110
at System.Web.UI.WebControls.
Button.OnC
lick(Event
Args e)
at System.Web.UI.WebControls.
Button.Rai
sePostBack
Event(Stri
ng eventArgument)
at System.Web.UI.WebControls.
Button.Sys
tem.Web.UI
.IPostBack
EventHandl
er.RaisePo
stBackEven
t(String eventArgument)
at System.Web.UI.Page.RaisePo
stBackEven
t(IPostBac
kEventHand
ler sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePo
stBackEven
t(NameValu
eCollectio
n postData)
at System.Web.UI.Page.Process
RequestMai
n(Boolean includeStagesBeforeAsyncPo
int, Boolean includeStagesAfterAsyncPoi
nt)
InnerException:
View the Solution FREE for 7 Days