使用vb.net导出到csv,gridview1.columns.count等于0列

时间:2014-06-27 00:26:20

标签: vb.net csv gridview export

我在代码中创建了一个数据表,然后将gridview绑定到此数据表。我的数据完美地显示在gridview中。当我使用我在此论坛中找到的函数导出到csv时,导出的文件为空,我注意到它显示gridview有0列。我尝试将自动生成列设置为false但这会导致我的gridview不显示任何数据,但导出仍为空白。

Imports System.IO

Partial Class Default3
    Inherits System.Web.UI.Page
    Dim dt As New Data.DataTable


    Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
        ' Verifies that the control is rendered

    End Sub

    Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
        Response.Clear()
        Response.Buffer = True
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.csv")
        Response.Charset = ""
        Response.ContentType = "application/text"
        GridView1.AllowPaging = False
        GridView1.DataSource = dt
        GridView1.DataBind()
        Dim sb As New StringBuilder()
        For k As Integer = 0 To GridView1.Columns.Count - 1
            'add separator
            sb.Append(GridView1.Columns(k).HeaderText + ","c)
        Next
        'append new line
        sb.Append(vbCr & vbLf)
        For i As Integer = 0 To GridView1.Rows.Count - 1
            For k As Integer = 0 To GridView1.Columns.Count - 1
                'add separator
                sb.Append(GridView1.Rows(i).Cells(k).Text + ","c)
            Next
            'append new line
            sb.Append(vbCr & vbLf)
        Next
        Response.Output.Write(sb.ToString())
        Response.Flush()
        Response.End()
    End Sub

    Protected Sub Button2_Click(sender As Object, e As System.EventArgs) Handles Button2.Click
        Dim ta As New dsahonorlTableAdapters.MIEMBROS1TableAdapter
        Dim ds As New dsahonorl.MIEMBROS1DataTable
        Dim r As dsahonorl.MIEMBROS1Row
        ds = ta.GetData()

        dt.Columns.Add("Nombre", GetType(String))
        dt.Columns.Add("Id", GetType(String))
        dt.Columns.Add("Especialidad", GetType(String))
        Dim nombre, id, espe As String

        For Each r In ds
            nombre = r.NOMBREMIEMBRO
            espe = r.ESPECIALIDAD
            id = r.IDMIEMBRO
            dt.Rows.Add(nombre, id, espe)
        Next
        GridView1.DataSource = dt
        GridView1.DataBind()

    End Sub
End Class

1 个答案:

答案 0 :(得分:0)

Button2_Click中,您正在向dt填充数据,并将其绑定到GridView1 - 我假设这是正在运行的部分。但是,在Button1_Click中您将dt重新绑定到GridView1,但此时dt将为空。这是因为每次回发到服务器都会有一个Default3页面类的新实例。

您可以在dt中重新加载Button1_Click,就像您在Button2_Click中加载GridView1一样,但是您可能无法重新绑定Button1_Click(对不起) ,现在不在Visual Studio前面,所以我无法测试它,因为控件中的值会在视图状态下回发到服务器。即尝试从GridView1.DataSource = dt GridView1.DataBind() 删除这些行:

TextBox.Text

<强>更新

好的,所以我错了,数据源不会在回发中被记住(即使其他控件属性,如GridView)。对于那个很抱歉!因此,您需要每次重新绑定Page.Load,我发现在DataTable中最容易。您可以在ViewState中手动保存ViewState,也可以每次重新查询(如果它非常大,GridView大小可能会失控)。似乎DataTable列不会及时构建,也许直到它在管道中稍后呈现。

这是一个工作示例,显示了绑定,并使用<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="GridTest.aspx.vb" Inherits="SO_GridViewCSV.GridTest" %> <!DOCTYPE html> <html> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Button ID="Button1" runat="server" Text="Export" /> </div> <div> <asp:GridView ID="GridView1" runat="server"></asp:GridView> </div> </form> </body> </html> 进行导出。

GridTest.aspx

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            ViewState("GridViewData") = GetData()
        End If
        GridView1.DataSource = ViewState("GridViewData")
        GridView1.DataBind()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Response.Clear()
        Response.Buffer = True
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.csv")
        Response.Charset = ""
        Response.ContentType = "application/text"
        Dim sb As New StringBuilder()
        Dim data = DirectCast(ViewState("GridViewData"), DataTable)
        ' Add headers
        sb.AppendLine(String.Join(","c, data.Columns.Cast(Of DataColumn)().Select(Function(x) x.ColumnName)))
        ' Add data rows
        For Each r As DataRow In data.Rows
            sb.AppendLine(String.Join(","c, r.ItemArray))
        Next
        Response.Output.Write(sb.ToString())
        Response.Flush()
        Response.End()
    End Sub

    Private Function GetData() As DataTable
        Dim dt = New DataTable()
        dt.Columns.Add("ColA", GetType(String))
        dt.Columns.Add("ColB", GetType(String))
        dt.Columns.Add("ColC", GetType(String))
        For i = 1 To 10
            dt.Rows.Add("A" & CStr(i), "B" & CStr(i), "C" & CStr(i))
        Next
        Return dt
    End Function

End Class

GridText.aspx.vb

Public Class GridTest         继承System.Web.UI.Page

{{1}}