GridView with CheckBox – Select All and Highlight Selected Row

 

Introduction

To enable row selection in GridView, we can either include a Button control or CheckBox control. For example, selecting a row item to delete. Using CheckBox control will give a better user experience than a Button control and it is user friendly when we require multiple row selections. We can include checkbox in every row of GridView to enable selection of that particular row. To do this, we need to include a TemplateColumn that has a CheckBox control inside it. To enable “Select All” feature, we can include a checkbox inside the HeaderTemplate, which will give better experience than a Button control. Moving forward, this article will help us doing it from client side JavaScript Code.

 

When the user selects a CheckBox in a row, we can highlight the row by changing the row’s background color using JavaScript. Also, when the user clicks the checkbox in the header, we can select all the checkbox in the gridview. Refer the below figures.

Row Selection


Select All

 

Constructing GridView

Declare a GridView control with a TemplateColumn as the first column to include CheckBox control. Include BoundField for other fields to display in the GridView.  

<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#010101" BorderStyle="Groove" BorderWidth="1px" CellPadding="4">
<Columns>
  <asp:TemplateField HeaderText="Roles">
     <HeaderTemplate>
         <asp:CheckBox ID="chkAll" οnclick="javascript:SelectAllCheckboxesSpecific(this);" runat="server" />
     </HeaderTemplate>
      <ItemTemplate>
        <asp:CheckBox οnclick="javascript:HighlightRow(this);" ID="chkDelete" runat="server" />
     </ItemTemplate>
   </asp:TemplateField>
 <asp:BoundField DataField="Email" HeaderText="Email" ReadOnly="True" />
 <asp:BoundField DataField="FirstName" HeaderText="First Name" ReadOnly="True" />
 <asp:BoundField DataField="LastName" HeaderText="Last Name" ReadOnly="True" />
</Columns>
<FooterStyle BackColor="White" ForeColor="#330099" />
<RowStyle BackColor="White" ForeColor="#330099" />
<HeaderStyle BackColor="#F06300" Font-Bold="True" ForeColor="#FFFFCC" />
</asp:GridView>

 To highlight the selected row, we will have JavaScript function called HighLightRow() and call this function on onclick event of the CheckBox in ItemTemplate.

Refer the below JavaScript function which does that.

代码
function HighlightRow(chkB)

{

var IsChecked = chkB.checked;           

if(IsChecked)

  {

       chkB.parentElement.parentElement.style.backgroundColor='#228b22'; 

       chkB.parentElement.parentElement.style.color='white';

  }else

  {

       chkB.parentElement.parentElement.style.backgroundColor='white';

       chkB.parentElement.parentElement.style.color='black';

  }

}

 

 

Enabling Select All

If we see the rendered output of the GridView, it will be rendered as a HTML Table with ID as GridView ID.

Refer the below output.

<table cellspacing="0" cellpadding="4" rules="all" border="1" id="gvUsers" style="background-color:White;border-color:#010101;border-width:1px;border-style:Groove;border-collapse:collapse;">
              <tr style="color:#FFFFCC;background-color:#F06300;font-weight:bold;">
                     <th scope="col">
                            <input id="gvUsers_ctl01_chkAll" type="checkbox" name="gvUsers$ctl01$chkAll" οnclick="javascript:SelectAllCheckboxesSpecific(this);" />
                        </th><th scope="col">Email</th><th scope="col">First Name</th><th scope="col">Last Name</th>
              </tr><tr style="color:#330099;background-color:White;">
                     <td>
                            <input id="gvUsers_ctl02_chkDelete" type="checkbox" name="gvUsers$ctl02$chkDelete" οnclick="javascript:HighlightRow(this);" />
                        </td><td>test1@gmail.com</td><td>Babu</td><td>B</td>
//Goes on

So, we will first find the table from the rendered HTML and get all the checkbox inside table to check/uncheck depending on the state of the CheckBox control in header. Refer the below JavaScript function which selects all the checkbox inside the GridView when the Header CheckBox control is checked. 

代码
function  SelectAllCheckboxesSpecific(spanChk)

       {

           
var  IsChecked  =  spanChk.checked;

           
var  Chk  =  spanChk;

              Parent 
=  document.getElementById( ' gvUsers ' );          

              
var  items  =  Parent.getElementsByTagName( ' input ' );                         

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

              {               

                  
if (items[i].id  !=  Chk  &&  items[i].type == " checkbox " )

                  {           

                      
if (items[i].checked !=  IsChecked)

                      {    

                          items[i].click();    

                      }

                  }

              }            

       }

 

 Executing the page and see it in action.

Since, we are getting all the elements with tag name as “input”, the above code will check/uncheck the other CheckBox controls if present in any other column of the GridView control. To understand it better, include a checkbox at the last and execute the page. It will Check/Uncheck for the actions you do in the Header CheckBox. If you don’t have another checkbox control in the GridView, the above JavaScript code will work fine.

Refer the below figure.


 

To handle the above scenario with multiple CheckBox, we will change the code bit to check/uncheck the CheckBox control found based on the column location instead of checking all the CheckBox in the GridView. If we see the rendered HTML table, we have the checkbox at every first TD of the table. We will find the checkbox in every first TD and perform the required action. The below code does that.

代码
function  SelectAllCheckboxesMoreSpecific(spanChk)

       {

           
var  IsChecked  =  spanChk.checked;

           
var  Chk  =  spanChk;

              Parent 
=  document.getElementById( ' gvUsers ' );                                                   

              
for (i = 0 ;i <  Parent.rows.length;i ++ )

              {     

                  
var  tr  =  Parent.rows[i];

                 
// var td = tr.childNodes[0];                                  

                  
var  td  =  tr.firstChild;         

                  
var  item  =   td.firstChild;                     

                  
if (item.id  !=  Chk  &&  item.type == " checkbox " )

                  {           

                      
if (item.checked !=  IsChecked)

                      {    

                          item.click();    

                      }

                  }

              }            

       }

 

Configure the onclick event of header checkbox to point to the above JavaScript function.

The above code assumes the checkbox will be the first column of every row in the GridView. If the GridView have the selection CheckBox as the last column, then change the line which is bolded above to var item =  td.lastChild;

This code will work perfectly even if there are CheckBox controls present in any other column of the GridView control.

 

We can include a button that deletes the selected row, 

protected void btnDelete_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < gvUsers.Rows.Count;i++ )
        {
            CheckBox chbTemp = gvUsers.Rows[i].FindControl("chkDelete") as CheckBox;
            if (chbTemp.Checked)
            {
                Response.Write(gvUsers.Rows[i].Cells[1].Text + "<BR>");
                //Code for Deletion
 
            }
        }
    }

 

I took the example to delete the selected rows; it can be any operation that is specific to your requirement that can be done on the selected rows. 

 

 

 

 

 

转载于:https://www.cnblogs.com/wwyahead/archive/2010/12/17/1909687.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值