Web design, SQL, and .NET for the young, up-and-coming developer Dot Net Yuppie

Controls that are embedded in an ItemTemplate of a GridView can be tricky to reference in Javascript. For example, if you want to pass the ClientID of a textbox to a function, the following example will not work:


<script language="Javascript" type="text/javascript">
function AlertValue(SomeObject) {
    alert(SomeObject.value);
}
</script>
[...]
<asp:GridView ID="GridView1" runat="server">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:TextBox ID="SomeTextbox" runat="server"
                    onclick=’AlertValue(document.getElementById("<%# SomeTextbox.ClientID %>");’>
                </asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Why doesn’t it work?
You can’t use ASP.NET’s ClientID property to return the object because the server id ‘SomeTextbox’ is present in every row in the GridView — it’s not unique. You can reference ‘SomeTextbox’ in the code behind using the .FindControl method, but it’s much more involved than the work around below.

The optimal work around
By using Javascript’s ‘this’ keyword, we can reference the ‘SomeTextbox’ control within the ItemTemplate code. The ‘this’ keyword refers to the owner of the object that is using ‘this’ — for more information, check out Quirksmode - The this keyword. The following example is very similar to the above, incorrect example, except it uses Javascript to pass the ClientID to the ‘AlertValue’ function.


<script language="Javascript" type="text/javascript">
function AlertValue(SomeObject) {
    alert(SomeObject.value);
}
</script>
[...]
<asp:GridView ID="GridView1" runat="server">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:TextBox ID="SomeTextbox" runat="server"
                    onclick="AlertValue(this);"></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Using the ‘this’ keyword is a very basic in Javascript, but it can sometimes be easy to forget even the most basic things when you’re knee deep in ASP.NET and trying to solve a problem that is so simple it becomes complex.

One Response to “Self-Referencing Controls Within a GridView in Javascript”

  1. Wasin Says:

    How can I refer to Textbox ID=”txtMyDate” in Gridview using JavaScript?

    [Reply]

Leave a Reply