Vivek Thakur

Chaotically Complex

  Home  |   Contact  |   Syndication    |   Login
  105 Posts | 1 Stories | 498 Comments | 65 Trackbacks

News



Archives

ASP.NET Ventures

I have answered many questions on this topic so thought of writing a post on the same explaining the code on handling checkboxes with a Datagrid control.

Let's say you have a DataGrid  (id=dgUsers) with a column as a checkbox. Here is the ASPX code:

 <asp:datagrid id="dgUsers" runat="server" Width="100%" DataKeyField="userId" AutoGenerateColumns="False"
        OnPageIndexChanged="NewPage" PageSize="50" AllowPaging="True">
        <Columns>
         <asp:TemplateColumn>
           <HeaderTemplate>
             <table cellspacing="1" class="list-table">
               <tr>
                   <th width="50px" align="center">
                        Mark</th>
               <!--other columns headers... -->
           </HeaderTemplate>
<ItemTemplate>
<tr>
 <td>               <asp:CheckBox ID="chkMark" runat="server"></asp:CheckBox>     </td>
<td><!--other columns -->
</ItemTemplate></asp:DataGrid>

Now suppose the user selects checks some items and presses a button. In the click event of that button we need to do some processing in the code behind based on the selected checked boxes. Here is the code for the same (in the button's click event handler):

foreach(DataGridItem dgItem in dgUsers.Items)
{
     CheckBox c = (CheckBox)dgItem.FindControl("chkMark");
   
if(c.Checked)
     {
          //do processing here    
}

Note that we are using the DataGridItem type object in the foreach loop iterating through the Items collection of the DataGrid.

Now what if you want to select/de-select all the checkboxes as once using Javascript? This can be done easily by iterating through the forms collection as shown in this article:

http://www.mastercsharp.com/article.aspx?ArticleID=81&&TopicID=2

 

posted on Wednesday, February 07, 2007 1:48 PM