This is my markup of GridView.
Try using this code, I had a similar problem. I think this code is more dynamic and you do not have to find the name of the label every time. But to keep the correspondence between the controls And the index Controls [ ]:
for (int row = 1; row <= totalRows; row++)
{
for (int col = 0; col < totalCols; col++)
{
if (GridView1.Columns[col].Visible)
{
if (String.IsNullOrEmpty(GridView1.Rows[row - 1].Cells[col].Text))
{
if (GridView1.Rows[row - 1].Cells[col].Controls[1].GetType().ToString().Contains("Label"))
{
Label LB = (Label)GridView1.Rows[row - 1].Cells[col].Controls[1];
workSheet.Cells[row + 1, col + 1].Value = LB.Text;
}
else if (GridView1.Rows[row - 1].Cells[col].Controls[1].GetType().ToString().Contains("LinkButton"))
{
LinkButton LB = (LinkButton)GridView1.Rows[row - 1].Cells[col].Controls[1];
workSheet.Cells[row + 1, col + 1].Value = LB.Text;
}
}
else
{
workSheet.Cells[row + 1, col + 1].Value = GridView1.Rows[row - 1].Cells[col].Text;
}
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;
{cell}.Text
will only work if there isn't a control within the TemplateField
. You have added a label to your template which is why you first need to find the control, cast your object to the control and access the control's properties as needed.
If you want a more generic approach you could always do the following (remove the label control and simply add the evaluated field):
<Columns>
<asp:TemplateField HeaderText="Customer Name">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "Customer.Name")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="PickUpPoint">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "Pickuppoint")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
When you use the code you initially used, the {cell}.Text
should no longer return empty.
For retrieving values do this:
for (int i = 0; i < GridView2.Rows.Count; i++)
{
//extract the TextBox values
Label lblname= (Label)GridView2.Rows[i].Cells[0].FindControl("lblname");
Label lblPickUpPoint= (Label)GridView2.Rows[i].Cells[0].FindControl("lblPickUpPoint");
//Do your excel binding here
}
protected void Button1_Click(object sender, EventArgs e)
{
int i = 0;
for (i = 0; i <= GvSchedule.Rows.Count - 1; i++)
{
if (((CheckBox)GvSchedule.Rows[i].FindControl("ChkIsService")).Checked)
{
string catName = ((Label)GvSchedule.Rows[i].FindControl("lblCatName")).Text;
var subCatName = ((Label)GvSchedule.Rows[i].FindControl("lblSubCatName")).Text;
}
}
}