【问题标题】:ASP.net C# GridView to html table not workingASP.net C# GridView 到 html 表不起作用
【发布时间】:2016-04-19 02:29:27
【问题描述】:

所以我有这个标记:

<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 上找到的,标题工作正常,但行返回 null。我使用它使用 ITextSharp 将 gridview 打印为 pdf。

此方法也适用于其他网格视图。我不知道为什么它在这个特定的 gv 上返回 null。

【问题讨论】:

  • 你确定你的gridview有行吗?

标签: c# asp.net gridview itextsharp


【解决方案1】:

对于带有 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

【讨论】:

  • 不客气!抱歉,我刚刚更正了 tr 标签,然后才注意到您的编辑“待定”(第一次有人编辑我的答案)。
  • 没关系!再次感谢您!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-04
  • 1970-01-01
  • 1970-01-01
  • 2018-04-11
  • 2017-02-24
相关资源
最近更新 更多