c# - ASP.net C# GridView 到 html 表不工作

标签 c# asp.net gridview itext

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

<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 类中:

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;
    }

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

此方法也适用于其他 gridview。我不知道为什么它会在这个特定的 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

关于c# - ASP.net C# GridView 到 html 表不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36707473/

相关文章:

c# - 数字后修剪字符串

c# - 如何滚动到 GridView 中的选定行

c# - 使用 HTTPWebRequest 对象调用 WebService

c# - GridView Column验证,显示错误信息不要松散焦点

asp.net - 如何在 ASP.Net Gridview 中添加 "confirm delete"选项?

c# - C# : How to do constructor chaining, 的初学者覆盖和使用 :this/:base?

C#:表示方法的可执行方式作为接口(interface)的一部分存在

c# - 2d 平台游戏敌人运动

c# - HttpWebRequest 未传递凭据

c# - 隐藏 Umbraco 属性