Access boundfield value in GridView from javascript

minglelinch
minglelinch used Ask the Experts™
on
I have a gridview defined as -
<asp:GridView ID="PGridView" runat="server" DataKeyNames="id"
   OnSelectedIndexChanged="PGridView_SelectedIndexChanged"
   OnDataBound="PGridView_DataBound">
   <Columns>
          <asp:CommandField HeaderText="Edit" SelectText="Edit" ShowSelectButton="True" />
          <asp:BoundField DataField="id" HeaderText="ID" />
          <asp:BoundField DataField="category" HeaderText="Device" />
             ... ...

I need to access the gridview value in javascript when the following button is clicked -              
<asp:Button ID="btnAss" runat="server" Text="Assign" Width="120px" Height="22px" OnClientClick="if(!evalBeforeAss()) return false;" onclick="btnAss_Click" />

Here's the javascript -
        function evalBeforeAss()
        {
            var gridViewCtlId = '<%=PGridView.ClientID%>';  
            var grid = document.getElementById(gridViewCtlId);  
            var gridLength = grid.rows.length;
            if(gridLength==null)          
            {
                alert("Please add a PPP to assign.");
                return false;
            }
            return true;  
        }

But I got the error - Microsoft JScript runtime error: Object required
at the line:
var gridLength = grid.rows.length;

I tried to access the gridview cell value, I also got the similar error. Please help. Thanks.
             
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Hi, try changing your function like this

  function evalBeforeAss()
        {
            var gridViewCtlId = '<%=PGridView.ClientID%>';  
            alert(gridViewCtlId);
            var grid = document.getElementById(gridViewCtlId);  
           alert(grid);
            var gridLength = grid.rows.length;
            if(gridLength==null)          
            {
                alert("Please add a PPP to assign.");
                return false;
            }
            return true;  
        }

this will show you wich ID is looking for, so open the Page Source Code from your browser and see if the PGridView.ClientID is the same.

When you get this error, how many rows are in the GridView?

Author

Commented:
Thanks for your great answer. alert(grid) shows null, as 0 row in gridview.
I changed the code below. IT works as expected.

  var gridViewCtlId = '<%=PGridView.ClientID%>';  
  var grid = document.getElementById(gridViewCtlId);  
  if(grid!=null)          
  {
                alert("Please add a PPP to assign.");
                return false;
  }
  return true;  
       

Author

Commented:
Thanks for the great cooment.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial