oren_danniel
oren_danniel

Reputation: 25

asp.net template field get cell text using find control doesn't work

I know that this question was asked many times before but I couldn't find an answer which solves my problem.

I need to do something very basic and simple, I have a GridView which has a template field and I am trying to access a cell text in the GridView,

So I have tried the following:

C#

Label lbl = GridView1.SelectedRow.Cells[0].FindControl("lblSomething") as Label;
string customerName = lbl.Text;

html

<Columns>
    <asp:CommandField ShowSelectButton="True" />
    <asp:TemplateField SortExpression="Item">
    <HeaderTemplate>
         <asp:LinkButton ID="lblSomething" runat="server" Text="title" CommandName="Sort" CommandArgument="Something" ForeColor="white"></asp:LinkButton><br />
         <asp:TextBox runat="server" ID="Something" AutoPostBack="false" Width ="60" autocomplete="off"></asp:TextBox>                    
    </HeaderTemplate>
    <ItemTemplate>
        <%#Eval("Something") %>
    </ItemTemplate>
    <ItemStyle Width="80px" />
    </asp:TemplateField>

lbl returns null.

Can someone please explain to me how to use FindControl? Try to be as clear as you can.

Upvotes: 0

Views: 510

Answers (1)

VDWWD
VDWWD

Reputation: 35564

Your LinkButton is in the HeaderRow, not a normal row. You need to use FindControl on the header.

LinkButton lb = GridView1.HeaderRow.FindControl("lblSomething") as LinkButton;

And make sure you cast the right type. You are searching for a Label, but lblSomething is a LinkButton.

Upvotes: 2

Related Questions