简体   繁体   中英

ASP.NET DataGrid ClientID value returning null

I see that there were lot of questions on getting ClientID in ASP.NET but all the questions that I've looked did not help for my scenario. I'm a bit new to ASP.NET and have issues in getting the ClientID of a DataGrid in JavaScript.

Hope someone in this forum help me to find a way.

On my aspx page, I got a datagrid:

 <div class="tblgrid" id="divItems">
    <asp:DataGrid ID="dgItems" runat="server" AutoGenerateColumns="False" GridLines="None">
    <Columns>
         <asp:BoundColumn HeaderText="EmpId" DataField="EmpId">
         </asp:BoundColumn>
         <asp:BoundColumn HeaderText="F_Name" DataField="F_Name">
         </asp:BoundColumn>
         <asp:BoundColumn HeaderText="L_Name" DataField="L_Name">
         </asp:BoundColumn>
         <asp:BoundColumn DataField="City" HeaderText="City">
         </asp:BoundColumn>
         .....
    </Columns>

When I'm using the following in my JavaScript, it is returning appropriate table inner HTML in the alert message.

  alert(document.getElementById('ct100_PageContent_dgItems').innerHTML);

but when I'm using the ASP.NET ClientID, I'm getting a null value exception because it is throwing a null value.

  alert(document.getElementById('<%=dgItems.ClientID %>').innerHTML); 

Can anyone help me in this regard.

Thanks in advance.

If the document.getElementById('<%=dgItems.ClientID %>') is in a separate JS file to that of the aspx page, then the ASP.Net engine will not be able to resolve the reference. It only works for scripts embedded within the .aspx page.

A solution however is if you aren't duplicating the DataGrid on the page then you could give it a static id using ClientIDMode="static" :

<asp:DataGrid ID="dgItems" ClientIDMode="static" runat="server" AutoGenerateColumns="False" GridLines="None">

and then reference it with

document.getElementById('dgItems')

Instead of

alert(document.getElementById('<%=dgItems.ClientID %>').innerHTML);

.. you could give the DataGrid a CSS class, for example 'dgrid' and use a jQuery class selector to find it client side ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM