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.

Read the rest of this entry »