GridView CheckBox Selection With a Twist

原创 2007年09月23日 20:56:00
 

Introduction:

 

In one of my articles I discussed how to select checkboxes inside the GridView control. You can view the article here.  This is an extension to that article in which, I will discuss some additional features. These features include using regular expression to limit the checkbox selection on a particular GridView and de-selecting the parent checkbox when all child checkboxes are un-checked.

 

Creating the GridView Control:  

 

The first task is to create a simple GridView control using template fields. I strongly recommend using template fields instead of bound fields for the following reasons.

 

1)    Template fields allow embedding the ASP.NET controls.

2)    You don’t have to reorganize the appearance of the GridView after a new template field is added. This is because template field do not depend on the index number like the bound fields.

3)    Template fields allow access to ASP.NET controls even if the fields are not visible.

 

Finally, here is the code for the GridView control.

 

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">

       

        <Columns>

       

         <asp:TemplateField>

        

         <HeaderTemplate>

         <input type="checkbox" id="chkAll" name="chkAll" onclick="Check(this)" />

         </HeaderTemplate>

        

        <ItemTemplate>

        <asp:CheckBox ID="chkSelect" runat="server" />

        </ItemTemplate>

        </asp:TemplateField>

       

       

        <asp:TemplateField>

        <ItemTemplate>

        <asp:Label ID="lblCategoryName" runat="server" Text = '<%# Eval("CategoryName") %>' />

        </ItemTemplate>

        </asp:TemplateField>

       

        </Columns>

       

        </asp:GridView>

 

The HeaderTemplate contains the HTML checkbox and serves as the parent checkbox. The ItemTemplate contains the ASP.NET checkboxes. 

 

Populating the GridView Control:

 

I have used DataSet to populate the GridView control but you can use any type of container object to complete the task.

 

private void BindData()

    {

        string connectionString = "Server=localhost;Database=Northwind;Trusted_Connection=true";

        SqlConnection myConnection = new SqlConnection(connectionString);

        SqlDataAdapter ad = new SqlDataAdapter("SELECT CategoryID, CategoryName FROM Categories", myConnection);

 

        DataSet ds = new DataSet();

        ad.Fill(ds);

 

        GridView1.DataSource = ds;

        GridView1.DataBind();

    }

 

Now, if you run the application you will see the GridView displayed on the page.

 

 

NOTE: I have added styles to make the GridView look pretty!

 

Selecting and Deselecting CheckBoxes:

 

At this point your GridView control is displayed on the page and we need to implement the functionality to select and deselect all the child checkboxes when the parent checkbox is checked.

 

If you take a look at the GridView HTML code you will notice that the parent checkbox (chkAll) fires the Check function when clicked. Let’s see the Check function implementation.

 

function Check(parentChk)

{

    var elements =  document.getElementsByTagName("INPUT");

   

    for(i=0; i<elements.length;i++)

    {

        if(parentChk.checked == true)

        { 

            if( IsCheckBox(elements[i]) && IsMatch(elements[i].id))

            {

            elements[i].checked = true;

            }        

        }

        else

        {

            elements[i].checked = false;

        }      

    }   

      

}

 

The Check function is responsible for selecting and deselecting all the child checkboxes. First, I retrieve all the objects whose tag name is “INPUT”. Inside the loop I check that if the parent checkbox is checked or not. If it is checked then I find the correct checkbox element and mark it checked. The functions IsCheckBox and IsMatch are responsible for finding the child checkboxes.

 

Before I explain the working of the two methods let’s see your little regular expression which separates the GridView checkboxes from other checkboxes on the page and even from the checkboxes inside other GridView controls.

 

Here is out little regular expression:

 

var pattern = '^GridView1';

 

The expression says that select every string whose name starts with “GridView1”. You might be thinking that how does this expression help to find the correct child checkboxes. In order to understand it let’s take a look at the HTML code that is generated when the GridView is rendered on the page.

 

 

You can see that the checkboxes inside the GridView control are assigned unique ids. The first part contains the id of the GridView which, in this case is “GridView1”. The middle part contains the row number and the final part contains the original id of the checkbox as set by the developer.

 

Now, let’s take a look at the IsMatch function which, takes the id of the control as a parameter and returns true if matched else returns false.

 

function IsMatch(id)

{

    var regularExpresssion = new RegExp(pattern);

   

    if(id.match(regularExpresssion)) return true;

    else return false;

}

 

The IsMatch function is not enough. Huh! The reason is that we are not checking for the type of the element. The element which has the “INPUT” tag can be a checkbox, radio, textbox, button etc. For that reason there is another small method called IsCheckBox which simply checks for type of the element.

 

 

function IsCheckBox(chk)

{

    if(chk.type == 'checkbox') return true;

    else return false;

}

 

All the code that we have discussed will allow you to check and uncheck all the checkboxes based on the parent checkbox. The code also checks for the particular GridView so, that other checkboxes on the page are not affected.

 

Attaching Listeners to the Child CheckBoxes:

 

Listeners allow you to catch events generated by the controls and take action on those events by firing a function. Scott Andrew wrote an excellent piece of code that attaches the listeners to the object. The code is browser compatible (I have tested on Mozilla and IE).

 

function AddEvent(obj, evType, fn)

{

    if (obj.addEventListener)

    {

    obj.addEventListener(evType, fn, true);

    return true;

    }

 

 else if (obj.attachEvent)

 {

    var r = obj.attachEvent("on"+evType, fn);

    return r;

 }

  else

   {

    return false;

   }   

}

 

I won’t be explaining the insights of this function but if you are really interested then you should check out this link.

 

The AddEvent function is fired from the function AttachListener.

 

function AttachListener()

{

    var elements =  document.getElementsByTagName("INPUT");

   

    for(i=0; i< elements.length; i++)

    {      

        if( IsCheckBox(elements[i]) &&  IsMatch(elements[i].id))

        {

            AddEvent(elements[i],'click',CheckChild);

        }

    }   

}

 

In the code above I am registering the ‘click’ event of the checkboxes with a listener. Any time the click event is fired from the child checkboxes the “CheckChild” function is fired. The AttachListener is fired on the <body onload="AttachListener()"> event.

 

The CheckChild Function:

 

The CheckChild function keeps track of how many child checkboxes are checked. When all the child checkboxes are checked then the parent checkbox should also be checked.

 

function CheckChild(e)

{

    var evt = e || window.event;

   

    var obj = evt.target || evt.srcElement

 

    if(obj.checked)

    {

        if(counter < GetChildCheckBoxCount())

            { counter++; }       

    }   

           

    else

    {

       if(counter > 0) { counter--; }   

    }

      

    if(counter == GetChildCheckBoxCount())

    { document.getElementById("chkAll").checked = true; }

    else if(counter < GetChildCheckBoxCount()) { document.getElementById("chkAll").checked = false; }   

 

}

 

The total of checked checkboxes is stored in the global variable called “counter”. Once, the counter reaches the total child checkboxes then the parent checkbox is checked. With the global variable counter in-place there is also a small change in the Check function. Take a look at the final Check function.  

 

function Check(parentChk)

{

    var elements =  document.getElementsByTagName("INPUT");

   

    for(i=0; i<elements.length;i++)

    {

        if(parentChk.checked == true)

        { 

            if( IsCheckBox(elements[i]) &&  IsMatch(elements[i].id))

            {

            elements[i].checked = true;

            }        

        }

        else

        {

            elements[i].checked = false;

            // reset the counter

            counter = 0;

        }      

    }

   

    if(parentChk.checked == true)

    {

        counter = GetChildCheckBoxCount();

    }  

      

}

 

Few, extra lines are added to reset the counter. The method GetChildCheckBoxCount() is pretty simple and you can view the source in the download.

 

Here is the small animation of the effect:

 

 

I hope you liked the article, happy coding!

 

[Download Sample]

 

 

Gridview的Item嵌套CheckBox的另一种实现,避免了选中错乱等问题

GridView或者ListView的item布局嵌套checkBox选中数据错乱的问题解决。此处实现了GridView 其实listview类似...
  • guiping_ding
  • guiping_ding
  • 2015年11月16日 18:26
  • 1502

asp.net gridview中添加checkbox列,用于全部选中记录或取消全选

方法一:使用javascript代码控制                          前台代码:...
  • nvhaixx
  • nvhaixx
  • 2013年10月08日 14:03
  • 4595

ListView/GridView嵌套CheckBox滑动时CheckBox选中状态显示错乱

在讨论这个问题之前应该先了解ListView的复用机制  ListView复用的原理:ListView中的每一个Item显示都需要Adapter调用一次getView的方法,这个方法会传入一个con...
  • qq_30219217
  • qq_30219217
  • 2017年12月12日 16:13
  • 77

Android中ListView、GridView里的CheckBox混乱且记录选中数量不准确的解决方案

大家好,将今天遇到的一个ListView或GridView中含有CheckBox时,CheckBox选中状态混乱的问题的解决方案记录一下,希望对大家有些帮助。 开发中常常会有ListView或者Gr...
  • haunghui6579
  • haunghui6579
  • 2014年07月20日 11:19
  • 2319

ASP.NET GridView动态显示隐藏列,并保存客户的配置(用户控件Cookie版)

新建用户控件GridViewLayout.ascx
  • qq285679784
  • qq285679784
  • 2017年04月21日 20:25
  • 761

DevExpress GridControl使用教程:添加checkbox复选框

一、如何解决单击记录整行选中的问题 View->OptionsBehavior->EditorShowMode 设置为:Click 二、如何新增一条记录 (1)、gridView.A...
  • nieweiking
  • nieweiking
  • 2014年09月08日 19:50
  • 6067

GridControl 选择列、复选框全选(上)

说明:     GirdControl 中添加一列,这一列不是写在数据库中的,而是代码中添加的。 图示:   底层类代码: #region GridControl 全选 /// ...
  • u013816709
  • u013816709
  • 2015年07月01日 17:20
  • 7121

GridView控件中添加CheckBox控件,并且实现选择、全选和反选

一、如何在GridView中添加CheckBox控件?      1、添加一个GridView控件后,单击向右箭头,选择【编辑列】;      2、在弹出的【字段】窗口中,选择TemplateFiel...
  • u010276845
  • u010276845
  • 2013年10月19日 20:09
  • 1149

ROS中用Twist消息控制机器人

ROS中用Twist消息控制机器人INSTALLING THE ROS-BY-EXAMPLE CODE是书中第五章的内容,如果我们按照上一篇教程执行过了,就可以直接进入第五章,安装一个叫rbx1的包。...
  • lizilpl
  • lizilpl
  • 2015年07月04日 21:30
  • 6637

ROS探索(6)——C++控制SmartCar

ROS探索之CPP控制SmartCar
  • hyhop150
  • hyhop150
  • 2016年05月26日 22:16
  • 867
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:GridView CheckBox Selection With a Twist
举报原因:
原因补充:

(最多只允许输入30个字)