ASP.net C# GridView 到 html table 不工作

ASP.net C# GridView to html table not working

所以我在我的标记上有这个:

<asp:GridView ID="GridView1" runat="server" ItemType="IR_InfantRecord.Models.Immunization" DataKeyNames="ImmunizationNumber" SelectMethod="patientImmunGrid_GetData" AutoGenerateColumns="False" 
            ...
            <Columns>

                <asp:TemplateField HeaderText="EmpName">
                    <ItemTemplate>
                    <asp:Label Text="<%# Item.Emp.EmpName%>"
                        runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="Check">
                    <ItemTemplate>
                    <asp:Label Text="<%# Item.Emp.Check%>"
                        runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>

                <asp:DynamicField DataField="Status" />
                <asp:DynamicField DataField="DateTaken" />            

            ...
        </asp:GridView>

在我的 .cs 上 class:

public static string ConvertGVToHTML(GridView gv)
    {
        string html = "<table>";
        //add header row
        html += "<tr>";
        for (int i = 0; i < gv.Columns.Count; i++)
            html += "<td>" + gv.Columns[i].HeaderText + "</td>";
        html += "</tr>";
        //add rows
        for (int i = 0; i < gv.Rows.Count; i++)
        {
            html += "<tr>";
            for (int j = 0; j < gv.Columns.Count; j++)
                html += "<td>" + gv.Rows[i].Cells[j].Text.ToString() + "</td>";
            html += "</tr>";
        }
        html += "</table>";
        return html;
    }

我在 Whosebug 上找到的,header 工作正常,但行返回空值。我正在使用它使用 ITextSharp 将 gridview 打印为 pdf。

此方法也适用于其他gridview。我不知道为什么它 returns 在这个特定的 gv 上为 null。

对于带有 Label 的 TemplateField,值不在单元格文本中,而是在 Label 控件中(这是单元格的第二个控件,在 Literal 控件之后):

for (int i = 0; i < gv.Rows.Count; i++)
{
    html += "<tr>";

    for (int j = 0; j < gv.Columns.Count; j++)
    {
        TableCell cell = gv.Rows[i].Cells[j];

        html += "<td>";

        if (cell.Controls.Count > 1 && cell.Controls[1] is Label)
        {
            Label lblValue = cell.Controls[1] as Label;
            html += lblValue.Text;
        }
        else
        {
            html += cell.Text;
        }

        html += "</td>";
    }

    html += "</tr>";
}

顺便说一句,我保留了您的代码中所示的字符串连接技术,但最好使用 StringBuilder