我有从datagridview导出到Excel的功能,我通过按tab键点击界面上的每个按钮来进行测试,以定位每个按钮的指示器。但当按下导出按钮时。它会给我一个错误
DataGrid with id '' could not automatically generate any columns from the selected data source.但是当我用指针/鼠标点击它时,它工作得很好。
下面是我导出的excel代码:
Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExport.Click
        Dim dt As New DataTable
        If CInquiry.SearchInquiry(txtAccount.Text, txtCustName.Text, txtAmount.Text, dropResponse.SelectedValue.ToString, txtInquiryDate.Text) Then
            dt = CInquiry.DT
        Else
            eMessage(CInquiry.eMsg)
        End If
        Dim DataGrd As New DataGrid()
        DataGrd.DataSource = dt.DefaultView
        DataGrd.DataBind()
        Dim attachment As String
        attachment = "attachment; filename=Inquiry_Report" & Format(Now, "ddMMMyyyy") & ".xls"
        Response.Buffer = True
        Response.ClearContent()
        Response.ClearHeaders()
        Response.AddHeader("content-disposition", attachment)
        Response.ContentType = "application/ms-excel"
        Dim sw As New StringWriter()
        Dim htw As New HtmlTextWriter(sw)
        DataGrd.RenderControl(htw)
        Response.Write(sw.ToString())
        Response.End()
    End Sub错误是当datagrid试图绑定数据时,只有当我执行上面所说的操作时,才会引发错误。怎么了?它是否仅通过指针/鼠标单击?
发布于 2013-05-24 18:01:56
嗨,实际上我现在不知道VB代码,但我可以发布c#代码,这可能会对你有帮助
 protected void lnkfiledownload_Click(object sender, EventArgs e)
    {
        string attachment = "attachment; filename=notification.xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        // Create a form to contain the grid
        HtmlForm frm = new HtmlForm();
        gvBranchNotification.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(gvBranchNotification);
        frm.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }https://stackoverflow.com/questions/16731887
复制相似问题