kevin
kevin

Reputation: 14065

Unable to get value of the property 'length': object is null or undefined - Javascript Error

In my user control, there is a GridView. When I check checkbox in the header of the GridView, I want to select all checkboxs. My user control can be use more than once in a page. So I try like this.

My GridView

<asp:GridView ID="GridView" runat="server">
    <Columns>
        <asp:TemplateField>
            <HeaderTemplate>
                <asp:CheckBox ID="chkHeader" runat="server" />
            </HeaderTemplate>
            <ItemTemplate>
                <asp:CheckBox ID="chkEach" runat="server" />
            </ItemTemplate>
            .
            .

This is my C# codes

CheckBox chkAll = gvAttachment.Controls[0].Controls[0].FindControl("chkHeader") as CheckBox;
     if (chkAll != null)
     {
           chkAll.Attributes.Add("onclick", "SelectAllChkBox('" + chkAll.ClientID + "','" + GridView.ClientID + "');");
     }

This is my javascript

function SelectAllChkBox(value , grid) {
    for (var i = 1; i < grid.all.length; i++) {
        grid.all[i].checked = value.checked;
    }
}

But I got this error.

Unable to get value of the property 'length': object is null or undefined

What is wrong with my Code ?

Upvotes: 0

Views: 4065

Answers (3)

Codebeat
Codebeat

Reputation: 6610

An array starts from 0:

function SelectAllChkBox(value , grid) {
    for (var i = 0; i < grid.all.length; i++) {
        grid.all[i].checked = value.checked;
    }
}

Upvotes: 1

Ghost Answer
Ghost Answer

Reputation: 1498

try this function

function SelectAllChkBox(value , grid) {
    var n = document.getElementById("grid").rows.length;
    for (var i = 0; i < n; i++) {
        grid.all[i].checked = value.checked;
    }
}

Upvotes: 0

Asken
Asken

Reputation: 8041

The parameter grid is the id (a string) of the grid view which means you don't have an "all". length works on the "grid" though. You are not passing an object from c#.

You'll need to find all the check boxes client-side and set checked based on a true or false value.

Upvotes: 2

Related Questions