Web design, SQL, and .NET for the young, up-and-coming developer - Dot Net Yuppie �� » Javascript
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 »