开发者

Gridview Checking all checkboxes issue

I am using the gridview's select all checkbox feature from here. The script used here has one issue.

If i select the header checkbox, all the template (rows) checkbox gets selected. If i then deselect all the template checbox, the header checbox still remains checked. How to deselect the header checkbox in that case?

Please advi开发者_如何学Cce!


Firstly, I would add a Css Class to CheckBox1 for use later class="chk-all".

Then, add a javascript function to the ItemTemplate checkbox.

<ItemTemplate>
    <asp:CheckBox ID="CheckBox1" runat="server" onclick="UnselectAllOption()"  />
</ItemTemplate>

Then, using some jQuery to select the checkbox that has class="chk-all".

function UnselectAllOption(){  
    $('.chk-all').attr("checked", false");  
}

I set this to unchecked as soon as one of the other checkboxes is clicked because either none are selected and you are selecting a single one, so the checkbox in the HeaderTemplate should not be checked. OR all the checkboxes are already checked which means that the one in the HeaderTemplate should not be checked as you are changing one of the others to not being checked.

edit

p.s. this answer requires you to add a script reference to the jQuery javascript library.


This is the .NET way, however jQuery solutions are much cleaner:

Script:

 function resetParent(parentRow)
 {
    document.getElementById(parentRow).checked = false;
 }

Markup:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
    Caption="Pick Some Technologies" BackColor="White" BorderColor="#CC9966" OnRowDataBound="ObjectDataSource1__RowDataBound"
    BorderStyle="None" BorderWidth="1px" CellPadding="4">
    <Columns>
    <asp:TemplateField HeaderText="Include" SortExpression="Include">
        <HeaderTemplate>
        <asp:CheckBox ID="CheckBox1" runat="server" onclick="changeAllCheckBoxes(this)" />
        </HeaderTemplate>
        <ItemTemplate>
        <asp:CheckBox ID="CheckBox1" runat="server" />
        </ItemTemplate>
        <ItemStyle HorizontalAlign="Center" />
    </asp:TemplateField>
    <asp:BoundField DataField="Name" HeaderText="Technology" />
    </Columns>
    <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
</asp:GridView>

Code-behind:

private CheckBox parentCheckBox = null;
protected void ObjectDataSource1__RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        parentCheckBox = (CheckBox)e.Row.FindControl("CheckBox1");
    }    

    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        CheckBox childCheckBox = (CheckBox)e.Row.FindControl("CheckBox1");
        childCheckBox.Attributes.Add("onclick","resetParent('" + parentCheckBox.ClientID + "')");
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜