This is my markup of 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>
I have a button which stores the values in the worksheet cells of excel object.
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;
}
}
How do I get the values of GridView and store it in a worksheet, as the GridView2.Rows[i].Cells[j]
.Text returns empty string.
So, all you need to do is get the Cell's Control[0] or index of control based on your GridView to fetch the EVAL value. //--loop thru GridView1 Row and get the value rendered in ItemTemplate foreach (GridViewRow item in GridView1. Rows) Response.
Boundfield is a column bound direct to the datasource (column in a DB). A <asp:TemplateField /> is a customized column which can contain either a DB column as such or you may join together columns for display.
For example, the ItemTemplate is used by default to render the cell for each row, but the EditItemTemplate template can be used to customize the interface when editing data. In this tutorial we'll examine how to use the TemplateField to achieve a greater degree of customization with the GridView control.
Using DataKeyNames and DataKeys is fairly simple, you just need to set the name of the Column in DataKeyNames property as shown below. Here CustomerId is the name of the Column. And then in code access it using the RowIndex of the GridView Row to get the value of the Column for that particular Row.
Your are missing a type cast. Do it like this-
Label name = (Label)GridView2.Rows[i].Cells[j].FindControl("lblname");
xlWorkSheet.Cells[i + 1, j + 1] = name.Text;
Update- If you can name your labels as Label0 and Label1, then in the second for loop-
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;
}
For Header text- string hText = GridView2.HeaderRow.Cells[your column number].Text;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With