0

GridView に表示されている VB.Net で生成しているレポートがあります。データは、ユーザーが入力したいくつかの制約に基づいて SQL から取得され、これらに応じて任意のサイズにすることができます。これらの値をグリッドから取得し、SQL 選択を再実行せずにダウンロード可能なレポートの CSV に入れたい (その方法で構築する方法を知っている)、できれば一般的な方法で簡単に再利用できるようにしたい. これが私が現在持っているものです。CSV を作成しますが、ヘッダーのみが存在します。

Protected Sub btnExcel_Click(sender As Object, e As EventArgs) Handles btnExcel.Click
    Dim strOutput As New StringBuilder

    Response.ContentType = "application/csv"
    ' Remove the charset from the Content-Type header.
    Response.Charset = ""
    ' Turn off the view state.
    Me.EnableViewState = False
    Response.AddHeader("Content-Disposition", "filename=report.csv;")

    strOutput.AppendLine(GetCSVLine(grid.HeaderRow.Cells))
    For Each row As GridViewRow In grid.Rows
        strOutput.AppendLine(GetCSVLine(row.Cells))
    Next


    Response.Write(strOutput)

    Response.Flush()

    Response.End()
End Sub

Private Function GetCSVLine(cells As TableCellCollection) As String
    Dim returnValue As String = ""

    For Each cell As TableCell In cells
        returnValue += cell.Text + ","
    Next

    Return returnValue
End Function

そしてaspxページ

    <asp:GridView ID="grid" runat="server" EnableModelValidation="True" AutoGenerateColumns = "false">
                    <Columns>
                        <asp:TemplateField HeaderText="Name">
                            <ItemTemplate>
                                <asp:Label ID="lblName" runat="server" Text='<%# Bind("Name")%>'/>&nbsp;
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Location">
                            <ItemTemplate>
                                <asp:Label ID="lblLocation" runat="server" Text='<%# Bind("Location")%>'/>&nbsp;
                            </ItemTemplate>
                        </asp:TemplateField>
<!-- There are a few more fields after this, using the same structure -->
4

1 に答える 1

0

申し訳ありませんが、ここで頭のてっぺんを実行していますが、各行には内部にテキストがあるコントロールのセットが含まれているため、表のセルに対してLabelストレートを使用して内容を取得することはできないと思います。cell.Text

FindControl各行に対してメソッドを使用して関連するコントロールを取得し、取得する各コントロールのプロパティにアクセスして、CSV にプッシュする必要があるデータを取得する必要がある場合があります。何かのようなもの:

For Each row As GridViewRow In grid.Rows
    'In each row, find the control which contains the data and then get the text of the control
    Dim nameLabel As Label = CType(row.FindControl("lblName"), Label)
    Dim nameValue As String = nameLabel.Text

    'Once you have all the values, write out the StringBuilder like you are doing already
Next
于 2013-03-29T22:59:43.760 に答える