How do I find the Client ID of control within an ASP.NET GridView?

Keltex picture Keltex · Jul 15, 2009 · Viewed 58.8k times · Source

I have a asp:GridView which contains a asp:TextBox within a TemplateField. I would like to obtain it's ID for use in javascript. Something like this:

<asp:TemplateField>
    <ItemTemplate>
        <asp:TextBox ID="textDateSent" runat="server" />
        <input type="button" value='Today' 
            onclick="setToday('<%# textDateSent.ClientID %>');" />
    </ItemTemplate>
</asp:TemplateField>

But when I compile, I get an error:

The name 'textDateSent' does not exist in the current context

Anybody know how to get the client ID of this TextBox?

Answer

Chris Mullins picture Chris Mullins · Jul 15, 2009

Try this:

<asp:TemplateField>
    <ItemTemplate>
        <asp:TextBox ID="textDateSent" runat="server">
        </asp:TextBox>                      
       <input type="button" value='Today' onclick="setToday('<%# ((GridViewRow)Container).FindControl("textDateSent").ClientID %>');" /> 
    </ItemTemplate>
</asp:TemplateField>