如何从GridView中的模板字段中获取值?

San*_*eep 8 c# asp.net excel gridview templatefield

这是我的GridView标记.

<Columns>
    <asp:TemplateField HeaderText="Customer Name">
        <ItemTemplate>
            <asp:Label ID="lblname" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Customer.Name")%>'></asp:Label>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="PickUpPoint">
        <ItemTemplate>
            <asp:Label ID="lblPickUpPoint" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Pickuppoint")%>'></asp:Label>
        </ItemTemplate>
    </asp:TemplateField>
</Columns>
Run Code Online (Sandbox Code Playgroud)

我有一个按钮,将值存储在excel对象的工作表单元格中.

for (int i = 0; i < GridView2.Rows.Count; i++)
{
    for (int j = 0; j < GridView2.Rows[i].Cells.Count; j++)
    {
        xlWorkSheet.Cells[i + 1, j + 1] = GridView2.Rows[i].Cells[j].Text;
   }
}
Run Code Online (Sandbox Code Playgroud)

如何获取GridView的值并将其存储在工作表中,因为GridView2.Rows[i].Cells[j].Text返回空字符串.

Cde*_*eez 10

你缺少一个类型演员.像这样做-

Label name = (Label)GridView2.Rows[i].Cells[j].FindControl("lblname");
xlWorkSheet.Cells[i + 1, j + 1] = name.Text;
Run Code Online (Sandbox Code Playgroud)

更新 -如果您可以将标签命名为Label0和Label1,那么在第二个for循环中 -

for (int j = 0; j < GridView2.Rows[i].Cells.Count; j++)
  {
     Label xyz = (Label)GridView2.Rows[i].Cells[j].FindControl("Label"+j);
     xlWorkSheet.Cells[i + 1, j + 1] = xyz.Text;
  }
Run Code Online (Sandbox Code Playgroud)

对于标题文本 - string hText = GridView2.HeaderRow.Cells[your column number].Text;