Search code examples
javascriptasp.netlistboxselectedindex

javascript unable to set property selectindex list box


I have a list box which is binding in code behind, the user can select from the list and submit. The error that is occurring in the link button which clear this list from selecting is unable to set property 'selectedindex' of undefined or null reference

ASP.NET:

<asp:ListBox ID="lstBoxAgents" runat="server" SelectionMode="Multiple"></asp:ListBox>

<asp:LinkButton ID="lnkClearAgents" runat="server" 
 OnClientClick="document.getElementById('lstBoxAgents').selectedIndex = -1;return false;">
Clear Me</asp:LinkButton>

Solution

  • The Client ID of the ASP control is not necessarily the same as the ID you give it. ASP.NET prefixes your controls so that they don't collide, producing a Client ID. You can check what this ID is by opening your page in a browser and inspecting the element in F12 dev tools.

    It is possible to change the ClientID mode using the ClientIDMode property. If you set this to static, the client ID will always be the one you assign and you must ensure uniqueness yourself.