0

我有一个带有按钮的网格视图,用于将其数据导出到 Excel 文件。单击按钮时,我收到以下错误:

'GridView' 类型的控件'gvLogNotice' 必须放置在带有 runat=server 的表单标记内。

但是,网格位于表单标记内,我尝试使用 MasterPage 和使用不带 MasterPage 的页面,但仍然得到相同的错误。

这是我的带有按钮的 Gridview 片段:

<form id="form1" runat="server">
 <div style="width:600px;">
       <asp:GridView ID="gvLogNotice" 
        runat="server" 
        AutoGenerateColumns="false" 
        ShowFooter="false"
        OnRowCancelingEdit="gvLogNotice_RowCancelingEdit"
        OnRowEditing="gvLogNotice_RowEditing" 
        OnRowUpdating="gvLogNotice_RowUpdating"
        onpageindexchanging="gvLogNotice_PageIndexChanging"
        OnRowDataBound="gvLogNotice_RowDataBound"
        EmptyDataText="There are no data records to display."
        DataKeyNames="LogNoticeID"
        AllowPaging="true"
        PageSize="10"
        AllowSorting="true"
        OnSorting="gvLogNotice_sorting"
        Width="700px">
        <Columns>
            <asp:TemplateField HeaderText="Log No." Visible="false">
                <ItemTemplate>
                    <%#Eval("LogNoticeID")%>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtLogNoticeID" runat="server" Enabled="false" Text=' <%#Eval("LogNoticeID") %>'></asp:TextBox>
                </EditItemTemplate>
             </asp:TemplateField>
            <asp:TemplateField HeaderText="Log Date" SortExpression="DateLogged">
                <ItemTemplate>
                    <%#Eval("DateLogged")%>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtDateLogged" runat="server" Text=' <%#Eval("DateLogged") %>'></asp:TextBox>
                </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Log Description" HeaderStyle-Width="50px" sortexpression="LogNoticeDescript">
                <ItemTemplate>
                    <%#Eval("LogNoticeDescript")%>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtLogNoticeDescript" runat="server" Text=' <%#Eval("LogNoticeDescript") %>'></asp:TextBox>
                </EditItemTemplate>
           </asp:TemplateField>
           <asp:TemplateField HeaderText="Responsible Party" sortexpression="ResponsibleParty">
                <ItemTemplate>
                    <%#Eval("ResponsibleParty")%>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtResponsibleParty" runat="server" Text=' <%#Eval("ResponsibleParty") %>'></asp:TextBox>
                </EditItemTemplate>
          </asp:TemplateField>
             <asp:TemplateField HeaderText="Planned Date" SortExpression="PlannedDate" >
                <ItemTemplate>
                    <%#Eval("PlannedDate")%>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtPlannedDate" runat="server" Text=' <%#Eval("PlannedDate") %>'></asp:TextBox>
              </EditItemTemplate>
          </asp:TemplateField>
           <asp:TemplateField HeaderText="Case Number" SortExpression="CaseNumber">
                <ItemTemplate>
                    <%#Eval("CaseNumber")%>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtCaseNumber" runat="server" Text=' <%#Eval("CaseNumber") %>'></asp:TextBox>
              </EditItemTemplate>
          </asp:TemplateField>
             <asp:TemplateField HeaderText="Log Status" SortExpression="LogStatus">
                <ItemTemplate>
                    <%#Eval("LogStatus")%>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtLogStatus" runat="server" Text=' <%#Eval("LogStatus") %>'></asp:TextBox>
                    <asp:RangeValidator ID="rgvtxtLogStatus" runat="server" ControlToValidate="txtLogStatus" MaximumValue="1" MinimumValue="0" Text="Only a Value of 1 or 0 is allowed." />
                </EditItemTemplate>
          </asp:TemplateField>
            <asp:TemplateField HeaderText="Edit">
                <ItemTemplate>
                    &nbsp;&nbsp;
                    <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="images/edit.png" Width="25"
                        Height="25" CommandName="Edit" />&nbsp;&nbsp;
                   <%-- <asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/img/delete.png" CommandName="Delete"
                        OnClientClick="return confirm('Are you sure want to delete record?')" />--%>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Update">Update</asp:LinkButton>&nbsp;&nbsp;
                    <asp:LinkButton ID="LinkButton2" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
                </EditItemTemplate>
              </asp:TemplateField>
        </Columns>
    </asp:GridView>
    </div>

<div><asp:Button runat="server" ID="btnExport" Text="Export to Excel" 
            onclick="btnExport_Click" /></div>
</form>

...这是按钮背后的代码:

protected void btnExport_Click(object sender, EventArgs e)
    {


        Response.Clear();

    Response.AddHeader("content-disposition", "attachment;  filename=FileName.xls");


    Response.ContentType = "application/vnd.xls";

    System.IO.StringWriter stringWrite = new System.IO.StringWriter();

    System.Web.UI.HtmlTextWriter htmlWrite =
    new HtmlTextWriter(stringWrite);

    gvLogNotice.RenderControl(htmlWrite);

    Response.Write(stringWrite.ToString());

    Response.End();

    }

...第二种方法:我还尝试了以下方法,但我收到一个错误,即可能只存在一个表单:

 protected void btnExport_Click(object sender, EventArgs e)
  {

        try
        {
            Response.ClearContent();
            string attachment = "attachment; filename=MyExelFile.xls";
            Response.ClearContent();
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = "application/ms-excel";
            StringWriter strWrite = new StringWriter();
            HtmlTextWriter htmWrite = new HtmlTextWriter(strWrite);
            HtmlForm htmfrm = new HtmlForm();
            gvLogNotice.Parent.Controls.Add(htmfrm);
            htmfrm.Attributes["runat"] = "server";
            htmfrm.Controls.Add(gvLogNotice);
            htmfrm.RenderControl(htmWrite);
            Response.Write(strWrite.ToString());
            Response.Flush();
            Response.End();
        }
        catch (Exception ex) { }
}

我可以就我在这里缺少的东西寻求帮助吗?先感谢您。

4

5 回答 5

1

在导出按钮上尝试此代码:

 protected void btnExport_Click(object sender, EventArgs e)
{
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-excel";
    using (StringWriter sw = new StringWriter())
    {
        HtmlTextWriter hw = new HtmlTextWriter(sw);

        //To Export all pages
        GridView1.AllowPaging = false;
        GridViewBind();

        GridView1.HeaderRow.BackColor = Color.White;
        foreach (TableCell cell in GridView1.HeaderRow.Cells)
        {
            cell.BackColor = GridView1.HeaderStyle.BackColor;
        }
        foreach (GridViewRow row in GridView1.Rows)
        {
            row.BackColor = Color.White;
            foreach (TableCell cell in row.Cells)
            {
                if (row.RowIndex % 2 == 0)
                {
                    cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
                }
                else
                {
                    cell.BackColor = GridView1.RowStyle.BackColor;
                }
                cell.CssClass = "textmode";
            }
        }

        GridView1.RenderControl(hw);

        //style to format numbers to string
        string style = @"<style> .textmode { } </style>";
        Response.Write(style);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }
}
public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}
于 2013-09-20T08:18:01.880 回答
0

如果您喜欢使用 3rd 方组件,请参阅本文。

http://www.codeproject.com/Articles/8411/C-class-library-for-exporting-data-to-CSV-Excel-fi

于 2013-09-19T19:53:23.793 回答
0

尝试这个

protected void Button2_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition",
        "attachment;filename=GridViewExport.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.xls";
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.AllowPaging = false;
        GridView1.DataBind();
        GridView1.RenderControl(hw);
        string style = @"<style> .textmode { mso-number-format:\@; } </style>";
        Response.Write(style);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }
于 2013-09-19T20:43:03.317 回答
0
 private void ExportToExcel(DataTable dt)
        {
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=Sheet1.xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
            GridView dgGrid = new GridView();
            using (StringWriter sw = new StringWriter())
            {
                HtmlTextWriter hw = new HtmlTextWriter(sw);


                dgGrid.DataSource = dt;
                dgGrid.DataBind();

                dgGrid.HeaderRow.BackColor = Color.White;
                foreach (TableCell cell in dgGrid.HeaderRow.Cells)
                {
                    cell.BackColor = dgGrid.HeaderStyle.BackColor;
                }
                foreach (GridViewRow row in dgGrid.Rows)
                {
                    row.BackColor = Color.White;
                    foreach (TableCell cell in row.Cells)
                    {
                        if (row.RowIndex % 2 == 0)
                        {
                            cell.BackColor = dgGrid.AlternatingRowStyle.BackColor;
                        }
                        else
                        {
                            cell.BackColor = dgGrid.RowStyle.BackColor;
                        }
                        cell.CssClass = "textmode";
                    }
                }

                dgGrid.RenderControl(hw);

                //style to format numbers to string
                string style = @"<style> .textmode { mso-number-format:\@; } </style>";
                Response.Write(style);
                Response.Output.Write(sw.ToString());
                Response.Flush();
                Response.End();
            }
        }
于 2013-09-20T08:25:11.790 回答
0

当您的代码中没有VerifyRenderingInServerForm时,就会发生这种情况。

只需将此代码段放在您的导出代码之后,它就会消失。

 public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }
于 2014-08-19T19:02:37.190 回答