Question

Export Gridview to Excel not working

Asked by: perritomia

Hello, I have the following code, I put this into App_code.

 

public static void PrepareGridViewForExport(Control 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.Controls[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.Controls[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.Controls[i]);
                gv.Controls.AddAt(i, l);
            }
            if (gv.Controls[i].HasControls())
            {
                PrepareGridViewForExport(gv.Controls[i]);
            }

        }

    }

    public static void ExportGridView(GridView g1)
    {
        string attachment = "attachment; filename=Attachment.xls";
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.AddHeader("content-disposition", attachment);
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        g1.RenderControl(htw);
        HttpContext.Current.Response.Write(sw.ToString());
        HttpContext.Current.Response.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.VerifyRenderingInServerForm(Control control)
       at System.Web.UI.WebControls.GridView.Render(HtmlTextWriter writer, Boolean renderPanel)
       at System.Web.UI.WebControls.GridView.Render(HtmlTextWriter writer)
       at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter)
       at System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter)
       at System.Web.UI.Control.RenderControl(HtmlTextWriter writer)
       at ExcelHelper.ExportGridView(GridView g1) in c:\Inetpub\wwwroot\WebSite\App_Code\ExcelHelper.cs:line 67
       at ListDetails.Button3_Click(Object sender, EventArgs e) in c:\Inetpub\wwwroot\WebSite\DynamicData\CustomPages\Cities\ListDetails.aspx.cs:line 110
       at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
       at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  InnerException:

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2008-09-15 at 10:21:16ID23732698
Tags

ASP.NET

Topics

Programming for ASP.NET

,

.NET

,

.NET Framework 3.x versions

Participating Experts
4
Points
500
Comments
8

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. asp:literal using literal in ASP for iamges
    I am trying to develop some code I have had working in the past, but this code only allowed a images that are specified in the code to be displayed. To solve this I decided i would use a literal and C# (see below). The reason is i have the hover functionality working well i...
  2. export multi page gridview to excel
    hi, I'm trying to export the data from a gridview to an excel-file. I'm using the following code but it only gets the first page of the gridview, but of course I need them all. Can anyone help me in reading all of the data in the datagrid (or access the access-datasour...
  3. Problem in exporting Gridview to Excel
    I have a problem in IE,when am exporting gridview data to excel am getting an error shown in screenshot when am trying to open the excel sheet.plzzz help me out in solving this problem. Below is the code i have used in my application
  4. Is it possible to export a gridview to excel if there is a linkbu…
    I am trying to export a gridview to excel. I have a linkbutton inside my gridview. when i try to export the gridview to excel I get the following error. System.Web.HttpException: Control 'gvVacancy_ctl07_contractnumber' of type 'LinkButton' must be placed inside a form tag w...
  5. GridView
    Hey, I am trying to bind a Gridview to a table from SQL 2005 Database. It works fine at first, but the GridviEw doesnt show any values(columns) from the Database Table at all. It shows only the edit and Delete Button but No Information!! What can the problem be? How do i reso...
  6. private void blablaClick(object sender, EventArgs e), s…
    I had asked a question http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_24931311.html#a25913009 which is solved successfully. But while I am on the question, I need to figure out the source for the component: private void blablaClick(object sender, EventArgs e...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: the_bachelorPosted on 2008-09-15 at 10:37:32ID: 22480933

Looks like you're Missing the attribute runat = "server" in your <form> tag.
Or the form tag altogother.
Can you post your your aspx and aspx.cs files?

 

by: perritomiaPosted on 2008-09-15 at 11:17:57ID: 22481345

I dont think so.


 
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage"  %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
<title>Central de Servicios de Sodexo</title>
    <link rel="stylesheet" type="text/css" href="~/js/subModal/subModal.css" runat="server" />
    <!--[if IE 5]>
<style type="text/css"> 
/* place css box model fixes for IE 5* in this conditional comment */
.appBody #menuBar { width: 250px; }
</style>
<![endif]-->
<!--[if IE]>
<style type="text/css"> 
/* place css fixes for all versions of IE in this conditional comment */
.appBody #menuBar { padding-top: 30px; }
.appBody #mainContent { zoom: 1; }
/* the above proprietary zoom property gives IE the hasLayout it needs to avoid several bugs */
</style>
<![endif]-->
 
</head>
<body class="appBody">
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnableScriptGlobalization="true"  EnableScriptLocalization="true">
    </asp:ScriptManager>
<div id="container">
  <div id="header">
    <div id="logo">
      <h1>Logo</h1>
    </div>
    <div id="userInfo">
    <asp:LoginView ID="loginView" runat="server">
        <AnonymousTemplate>
            <asp:HyperLink ID="hlLogin" runat="server" NavigateUrl="~/Login.aspx" Text="Iniciar Sesión"/>
        </AnonymousTemplate>
        <LoggedInTemplate>
            Bienvenido: <%= Profile.Name + " " + Profile.LastName %><br />
            <asp:LinkButton ID="lnkLogout" runat="server" Text="Cerrar Sesión" 
                onclick="lnkLogout_Click" />
        </LoggedInTemplate>
    </asp:LoginView>
    </div>
  <!-- This clearing element should immediately follow the #userInfo div in order to force the #header div to contain all child floats -->
    <br class="clearfloat" />
    <div id="navBar">Central de Servicios</div>
    <!-- end #header -->
  </div>
  <div id="menuBar">
    <h3>Menú</h3>
    <ul>
      <li><a href="#">Link 1</a></li>
      <li><a href="#">Link 2</a></li>
      <li><a href="#">Link 3</a></li>
    </ul>
    <asp:Menu ID="menu" runat="server" DataSourceID="SiteMapDataSource1" Orientation="Vertical" />
    <!-- end #menuBar -->
  </div>
  
  <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" 
                    SiteMapProvider="AspNetSqlSiteMapProvider" />
               
  <div id="mainContent">
        <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
    <!-- end #mainContent -->
  </div>
  <!-- This clearing element should immediately follow the #mainContent div in order to force the #container div to contain all child floats -->
  <br class="clearfloat" />
  <div id="footer">
    <p><img src="~/img/logoParadigma.png" runat="server"/> Developed by <a href="http://www.paradigmasolutions.com" target="_blank">Paradigma Solutions</a></p>
    <!-- end #footer -->
  </div>
  <!-- end #container -->
</div>
    </form>
</body>
</html>
 
 
 
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" CodeFile="ListDetails.aspx.cs" Inherits="ListDetails" %>
 
<%@ Register src="~/DynamicData/Content/GridViewPager.ascx" tagname="GridViewPager" tagprefix="asp" %>
<%@ Register src="~/DynamicData/Content/FilterUserControl.ascx" tagname="DynamicFilter" tagprefix="asp" %>
 
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <asp:DynamicDataManager ID="DynamicDataManager1" runat="server" AutoLoadForeignKeys="true" />
 
    <h2>Ciudades<%--<%= GridDataSource.GetTable().DisplayName %>--%></h2>
 
    <asp:ScriptManagerProxy runat="server" ID="ScriptManagerProxy1" />
 
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <br />
            <table style="width: 100%">
                <tr>
                    <td align="center">
                        <asp:ValidationSummary ID="ValidationSummary1" runat="server" 
                            EnableClientScript="true" HeaderText="List of validation errors" ShowSummary="false" />
                        <asp:DynamicValidator ID="GridViewValidator" runat="server" 
                            ControlToValidate="GridView1" Display="None" />
                        <asp:DynamicValidator ID="DetailsViewValidator" runat="server" 
                            ControlToValidate="DetailsView1" Display="None" />
                        <asp:DetailsView ID="DetailsView1" runat="server"
                            DataSourceID="DetailsDataSource" DefaultMode="Insert" 
                            OnItemDeleted="OnDetailsViewItemDeleted" 
                            OnItemInserted="OnDetailsViewItemInserted" 
                            OnItemUpdated="OnDetailsViewItemUpdated" 
                            OnModeChanging="OnDetailsViewModeChanging" OnPreRender="OnDetailsViewPreRender" 
                            style="text-align: center" Width="100%" 
                            CellPadding="2" GridLines="None">
                            <RowStyle CssClass="row" />
                        
                            <Fields>
                                <asp:TemplateField ShowHeader="False">
                                    <InsertItemTemplate>
                                        <asp:Button ID="Button1" runat="server" CausesValidation="True" 
                                            CommandName="Insert" CssClass="submit" Text="Insertar" />
                                        &nbsp;<asp:Button ID="Button2" runat="server" CausesValidation="False" 
                                            CommandName="Cancelar" CssClass="submit" Text="Cancelar" />
                                    </InsertItemTemplate>
                                    <ItemTemplate>
                                        <asp:Button ID="Button1" runat="server" CausesValidation="False" 
                                            CommandName="New" CssClass="submit" Text="Nuevo" />
                                    </ItemTemplate>
                                     <EditItemTemplate>
                                        <asp:Button ID="Button1" runat="server" CausesValidation="True" 
                                            CommandName="Update" CssClass="submit" Text="Actualizar" />
                                        &nbsp;<asp:Button ID="Button2" runat="server" CausesValidation="False" 
                                            CommandName="Cancel" CssClass="submit" Text="Cancelar" />
                                    </EditItemTemplate>
                                </asp:TemplateField>
                            </Fields>
                            <HeaderStyle CssClass="tableHead" />
                        </asp:DetailsView>
                        <br />
                        <asp:FilterRepeater ID="FilterRepeater" runat="server">
                            <ItemTemplate>
                                <asp:Label runat="server" AssociatedControlID="DynamicFilter$DropDownList1" 
                                    Text='<%# Eval("DisplayName") %>' />
                                <asp:DynamicFilter ID="DynamicFilter" runat="server" 
                                    OnSelectedIndexChanged="OnFilterSelectedIndexChanged" />
                            </ItemTemplate>
                            <FooterTemplate>
                                <br />
                                <br />
                            </FooterTemplate>
                        </asp:FilterRepeater>
                        <asp:Button ID="Button3" runat="server" CausesValidation="False" 
                            onclick="Button3_Click" Text="Button" />
                        <br />
                        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
                            AllowSorting="True" AutoGenerateColumns="False" DataSourceID="GridDataSource" 
                            OnDataBound="OnGridViewDataBound" OnRowCreated="OnGridViewRowCreated" 
                            OnRowDeleted="OnGridViewRowDeleted" OnRowEditing="OnGridViewRowEditing" 
                            OnRowUpdated="OnGridViewRowUpdated" 
                            OnSelectedIndexChanging="OnGridViewSelectedIndexChanging" 
                            style="text-align: center; margin-right: 1px;" Width="100%" 
                            GridLines="None" onselectedindexchanged="GridView1_SelectedIndexChanged">
                            <PagerStyle />
                            <RowStyle CssClass="row" />
                            <Columns>
                                <asp:DynamicField DataField="Id" />
                                <asp:DynamicField DataField="Name" HeaderText="Nombre de La ciudad" />
                                <asp:DynamicField DataField="Branches" ShowHeader="false" />
                                <asp:TemplateField>
                                    <ItemTemplate>
                                        <asp:ImageButton  CommandName="Select" CausesValidation="false" ID="EditButton"  ImageUrl="~/App_Themes/SodexoTheme/ImageLibrary/icoEdit.png" runat="server"     Text="Editar" ToolTip="Editar"  />
                                        <asp:ImageButton  CommandName="Delete" CausesValidation="false" ID="DeleteButton1"  ImageUrl="~/App_Themes/SodexoTheme/ImageLibrary/icoDelete.png" runat="server"   Text="Eliminar" ToolTip="Eliminar"  OnClientClick='return confirm("Esta seguro que desea eliminar este registro");' />
                                    </ItemTemplate>
                                    <EditItemTemplate>
                                        <asp:ImageButton CommandName="Update" CausesValidation="true" ID="EditButton"  ImageUrl="~/App_Themes/SodexoTheme/ImageLibrary/icoEdit.png" runat="server"     Text="Actualizar"  ToolTip="Actualizar"  />
                                        <asp:ImageButton CommandName="Cancel" CausesValidation="false" ID="DeleteButton1"  ImageUrl="~/App_Themes/SodexoTheme/ImageLibrary/icoDelete.png" runat="server"    Text="Cancelar"  ToolTip="Cancelar"  />
                                    </EditItemTemplate>
                                </asp:TemplateField> 
                            </Columns>
                            <HeaderStyle CssClass="tableHead" />
                            <PagerTemplate>
                                <asp:GridViewPager runat="server" />
                            </PagerTemplate>
                            <EmptyDataTemplate>
                                No se encuentran registros.
                            </EmptyDataTemplate>
                            <AlternatingRowStyle CssClass="alternateRow" />
                        </asp:GridView>
                        <br />
                    </td>
                </tr>
            </table>
            <br />
 
            <asp:LinqDataSource ID="GridDataSource" runat="server" EnableDelete="true" EnableUpdate="true">
                <WhereParameters>
                    <asp:DynamicControlParameter ControlID="FilterRepeater" />
                </WhereParameters>
            </asp:LinqDataSource>
 
            <asp:Panel ID="DetailsPanel" runat="server">
              <br /><br />
 
              <asp:LinqDataSource ID="DetailsDataSource" runat="server" EnableDelete="true" EnableInsert="true" EnableUpdate="true">
                  <WhereParameters>
                      <asp:DynamicControlParameter ControlID="GridView1" />
                  </WhereParameters>
              </asp:LinqDataSource>
            </asp:Panel>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:

Select allOpen in new window

 

by: the_bachelorPosted on 2008-09-15 at 11:35:06ID: 22481563

From what I gather, your gridview is in a ContentPlaceHolder. (ListDetails.aspx)
Now I dont have your master page in oder to see whether it has a <Form> with runat="server" in it.
My guess is it DOES NOT
I can clearly see that ListDetails.aspx does not contain a <form> tag at all.
I'd suggest starting by wrapping one around the gridview just to see what happens with it...
Just give it a try, you can certainly undo it if you dont like it

 

by: Chirag1211Posted on 2008-09-15 at 11:37:07ID: 22481586

I think you should do following things in your code:

1. Add EnableEventValidation="false" attribute in your page directive of your page.

2. Add the following code in the code-behind file of your aspx page.

 public override void VerifyRenderingInServerForm(Control control)
        {

        }

This should solve this error.

Regards,

Chirag

 

by: perritomiaPosted on 2008-09-15 at 13:09:49ID: 22482359

Chirag1211: I dont want to put that code in the codebehind. Because I would have to paste it in 50 pages, Thats not an elegant solution.  

I tried it enableeventvalidation=false  but that didnt solve the problem.


the_bachelor: Your solution  didnt work either.  The master page has a form tag with runat=server.

it says

Server Error in '/WebSite' Application.
--------------------------------------------------------------------------------

A page can have only one server-side Form tag.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: A page can have only one server-side Form tag.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  

Stack Trace:

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage"  %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
<title>Central de Servicios de Sodexo</title>
    <link rel="stylesheet" type="text/css" href="~/js/subModal/subModal.css" runat="server" />
    <!--[if IE 5]>
<style type="text/css"> 
/* place css box model fixes for IE 5* in this conditional comment */
.appBody #menuBar { width: 250px; }
</style>
<![endif]-->
<!--[if IE]>
<style type="text/css"> 
/* place css fixes for all versions of IE in this conditional comment */
.appBody #menuBar { padding-top: 30px; }
.appBody #mainContent { zoom: 1; }
/* the above proprietary zoom property gives IE the hasLayout it needs to avoid several bugs */
</style>
<![endif]-->
 
</head>
<body class="appBody">
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnableScriptGlobalization="true"  EnableScriptLocalization="true">
    </asp:ScriptManager>
<div id="container">
  <div id="header">
    <div id="logo">
      <h1>Logo</h1>
    </div>
    <div id="userInfo">
    <asp:LoginView ID="loginView" runat="server">
        <AnonymousTemplate>
            <asp:HyperLink ID="hlLogin" runat="server" NavigateUrl="~/Login.aspx" Text="Iniciar Sesión"/>
        </AnonymousTemplate>
        <LoggedInTemplate>
            Bienvenido: <%= Profile.Name + " " + Profile.LastName %><br />
            <asp:LinkButton ID="lnkLogout" runat="server" Text="Cerrar Sesión" 
                onclick="lnkLogout_Click" />
        </LoggedInTemplate>
    </asp:LoginView>
    </div>
  <!-- This clearing element should immediately follow the #userInfo div in order to force the #header div to contain all child floats -->
    <br class="clearfloat" />
    <div id="navBar">Central de Servicios</div>
    <!-- end #header -->
  </div>
  <div id="menuBar">
    <h3>Menú</h3>
    <ul>
      <li><a href="#">Link 1</a></li>
      <li><a href="#">Link 2</a></li>
      <li><a href="#">Link 3</a></li>
    </ul>
    <asp:Menu ID="menu" runat="server" DataSourceID="SiteMapDataSource1" Orientation="Vertical" />
    <!-- end #menuBar -->
  </div>
  
  <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" 
                    SiteMapProvider="AspNetSqlSiteMapProvider" />
               
  <div id="mainContent">
        <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
    <!-- end #mainContent -->
  </div>
  <!-- This clearing element should immediately follow the #mainContent div in order to force the #container div to contain all child floats -->
  <br class="clearfloat" />
  <div id="footer">
    <p><img src="~/img/logoParadigma.png" runat="server"/> Developed by <a href="http://www.paradigmasolutions.com" target="_blank">Paradigma Solutions</a></p>
    <!-- end #footer -->
  </div>
  <!-- end #container -->
</div>
    </form>
</body>
</html>
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:

Select allOpen in new window

 

by: perritomiaPosted on 2008-09-15 at 13:12:28ID: 22482383

I tried moving    public  void ExportGridView(GridView g1) to the codebehind and that didnt work either.

I accept other ways to export my gridview to excel.

The only requirement is that I dont want to put the code to export in the codebehind, because that will duplicate a lot of code

Thx

 

by: BondinASPPosted on 2008-09-15 at 23:47:16ID: 22485451

Try this class .

using System;
using System.Data;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
 
/// <summary>
/// 
/// </summary>
public class GridViewExportUtil
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="fileName"></param>
    /// <param name="gv"></param>
    public static void Export(string fileName, GridView gv)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader(
            "content-disposition", string.Format("attachment; filename={0}", fileName));
        HttpContext.Current.Response.ContentType = "application/ms-excel";
 
        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {
                //  Create a table to contain the grid
                Table table = new Table();
 
                //  include the gridline settings
                table.GridLines = gv.GridLines;
 
                //  add the header row to the table
                if (gv.HeaderRow != null)
                {
                    GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
                    table.Rows.Add(gv.HeaderRow);
                }
 
                //  add each of the data rows to the table
                foreach (GridViewRow row in gv.Rows)
                {
                    GridViewExportUtil.PrepareControlForExport(row);
                    table.Rows.Add(row);
                }
 
                //  add the footer row to the table
                if (gv.FooterRow != null)
                {
                    GridViewExportUtil.PrepareControlForExport(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();
            }
        }
    }
 
    /// <summary>
    /// Replace any of the contained controls with literals
    /// </summary>
    /// <param name="control"></param>
    private static void PrepareControlForExport(Control control)
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
            Control current = control.Controls[i];
            if (current is LinkButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
            }
            else if (current is ImageButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
            }
            else if (current is HyperLink)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
            }
            else if (current is DropDownList)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
            }
            else if (current is CheckBox)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
            }
 
            if (current.HasControls())
            {
                GridViewExportUtil.PrepareControlForExport(current);
            }
        }
    }
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:

Select allOpen in new window

 

by: EleaorStarkPosted on 2009-02-16 at 13:37:49ID: 23654118

hello!

how can write image file to Excel or Word. So instead of removing I want passing the image to Excel/ Word.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...