My find control isn't finding a label in gridview item template, any ideas how can I fix this?

843 Views Asked by At

I am trying to attach a value to a label on my gridview using the same technique that I have used many times, even in this very page, but the find control isn't finding the label. Does anyone know why this might be? From the research that I've done I've come across some instances where having 2 labels in one item template causes this problem but in some cases, it doesn't.

Gridview:

<asp:TemplateField>
                    <ItemTemplate>
                        <asp:Label ID="lblStockDetailsS" runat="server"></asp:Label>
                        <asp:Label ID="lbl7" runat="server" Text="hello"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>

Code behind:

Label lblSD = (Label)e.Row.FindControl("lblStockDetailsS");
        lblSD.Text = Sline.StockDetailsS;

Label lblSD2 = (Label)e.Row.FindControl("lbl7");
        lblSD2.Text = Sline.NLocalStock;
1

There are 1 best solutions below

5
Rajesh On
  • The RowDataBound event will trigger on every rows in the grid.
  • You have check whether the current row is header or data row before finding the controls which is available in the data row.
  • Have your code block inside this condition.

    if(e.Row.RowType == DataControlRowType.DataRow)

Ref: https://techpattarai.com/findcontrol-onrowdatabound-csharp/

Thanks