Click here to Skip to main content
6,595,854 members and growing! (18,770 online)
Email Password   helpLost your password?
Web Development » ASP.NET » Howto     Beginner License: The Code Project Open License (CPOL)

The RIGHT Way to Use Checkboxes in a .NET Repeater!

By Sam Rahimi

How to generate checkboxes corresponding to items in a repeater, and how to retrieve their state on PostBack
C# 2.0, C# 3.0.NET 2.0, .NET 3.0, .NET 3.5, ASP.NET, Architect, Dev
Version:3 (See All)
Posted:8 Apr 2008
Updated:9 Feb 2009
Views:12,243
Bookmarked:13 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
13 votes for this article.
Popularity: 2.90 Rating: 2.61 out of 5
2 votes, 22.2%
1
2 votes, 22.2%
2
1 vote, 11.1%
3
4 votes, 44.4%
4

5

Update

It's one year later. I've gained some architectural insight, and to those who've been critical of this approach, I see your point. That said, the code here does work properly -  it's just highly inelegant.

Introduction 

ASP.NET server controls are designed to allow for event-driven programming and stateful behavior in the inherently stateless environment of the web. This is a good thing as it frees the programmer from having to parse Forms and QueryStrings and instead allows the developer to address visual elements on the page (i.e. text fields, drop down lists, labels, etc.) the same way you would deal with elements in a desktop application. The result is a huge savings of time, a nearly complete separation of UI and code, and an application that is far easier to debug.

Unfortunately, many of these controls are buggy and/or have missing features. Most notably, the <asp:CheckBox> control.

A common scenario in web development involves a list of checkboxes next to a bunch of items in a form. After submission of the form, the checked items are dealt with in some way (i.e. multiple deletion of messages in Hotmail.) Due to limitations in the CheckBox server control and a lack of documentation surrounding the proper use of Repeaters, developers have historically dealt with this problem by using a client side CheckBox, JavaScript, and an old-school cross page form post.

Background

The problem is fundamentally this: server side CheckBox controls lack a "Value" attribute. Therefore, it is difficult to use them with dynamically generated lists of data in a Repeater, as there is no straightforward way to determine which checkboxes represent which data item after the form is posted back.

There have been many solutions posted on the web which involve re-evaluating each data item in the repeater after PostBack using a looping approach. This method is error prone (such as with forward only readers) as well as being inefficient. The method I present here instead retrieves the data only once, stores it in a hidden server control paired with the checkbox, and allows for quick and easy retrieval on PostBack.

The Example

The following snippets show a typical example where a customer list is displayed, with a checkbox next to each customer. After the user clicks a button, messages are sent only to the customers who they have checked off.

The Front-End Code

 <asp:Repeater id="customerList" runat="server">
 <ItemTemplate>
    <%# Eval("name") %><br />  <!-- Their name -->
    <%# Eval("email") %><br /> <!-- Their email -->
    Send mailing list invite <asp:CheckBox id="selectUser" runat="server">
    <!-- Line below is key -->
    <asp:HiddenField ID="hiddenEmail" Value ='<%#Eval("email")%>'>
 </ItemTemplate>
 </asp:Repeater>

 <asp:Button Text="Send Message" OnClick="DoSend" Runat="server" />

What we have done here is place an invisible server control, the asp:HiddenField, inside the Repeater template. Since this control DOES allow a value to be assigned to it, we can now determine which checkbox is linked to which row.

To retrieve the email addresses associated with the checked items after PostBack, we need only to use a simple loop, as follows:

The Code-Behind

public void DoSend(object sender, EventArgs e)
{
    foreach (RepeaterItem i in customerList.Items)
       {                    
          //Retrieve the state of the CheckBox
          CheckBox cb = (CheckBox)i.FindControl("selectUser");
          if (cb.Checked)
          {
               //Retrieve the value associated with that CheckBox
               HiddenField hiddenEmail = (HiddenField)i.FindControl("hiddenEmail");

               //Now we can use that value to do whatever we want
               SendWelcomeMessage(hiddenEmail.Value);
          }
       }
} 

And that's all, folks! May the "I want to bang my head against the wall because I can't use a checkbox insider a repeater" phenomenon be but a distant memory.

Points of Interest

Microsoft has put a lot of work into its GridView control (for example, this particular problem is not an issue there) but really neglected its Repeater, which hasn't even changed significantly since ASP.NET 2.0.

Many coders choose the GridView over the Repeater partly for this reason. Repeaters are far more lightweight, and allow for full control over what is rendered. Hopefully this workaround will help to encourage its use.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Sam Rahimi


Member
Sam Rahimi is the lead developer for the interactive division of Supernova Entertainment group, and directs development for their social networking site, Supernova.com

He has years of experience with Microsoft development technologies, starting with classic ASP, and now develops in ASP.NET 3.5. A longtime VB programmer, Rahimi now swears by C# . In his code, he focuses on clarity, simplicity, and reusability, and loves to teach these techniques to other developers.

He also has extensive experience in the mobile industry; specifically, with the development of interactive SMS applications, optimization of websites for mobile use, and the development of J2ME applications for the phone.
Occupation: Team Leader
Company: Supernova Interactive
Location: Canada Canada

Other popular ASP.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 20 of 20 (Total in Forum: 20) (Refresh)FirstPrevNext
AnswerI found an easier solution Pinmemberfreecellwizard5:35 18 Jun '09  
GeneralRe: I found an easier solution Pinmemberfreecellwizard5:43 18 Jun '09  
GeneralInheritance? Why? Pinmemberotijim6:58 12 May '09  
Generalgood 1 Pinmemberashu2chandra22:17 17 Jun '08  
GeneralAnother option is... Pinmembertkrafael_net6:19 9 Apr '08  
GeneralRe: Another option is... PinmemberSam Rahimi7:55 9 Apr '08  
GeneralRe: Another option is... Pinmembertkrafael_net9:07 9 Apr '08  
GeneralInheritance? PinmemberRogic1:35 9 Apr '08  
GeneralRe: Inheritance? Pinmemberevolved3:24 9 Apr '08  
GeneralRe: Inheritance? PinmemberSam Rahimi4:59 9 Apr '08  
GeneralRe: Inheritance? Pinmemberevolved7:51 9 Apr '08  
GeneralRe: Inheritance? PinmemberSam Rahimi8:10 9 Apr '08  
GeneralRe: Inheritance? Pinmemberevolved8:22 9 Apr '08  
RantRe: Inheritance? Pinmembertkrafael_net9:15 9 Apr '08  
GeneralRe: Inheritance? PinmemberSam Rahimi12:18 9 Apr '08  
GeneralRe: Inheritance? Pinmembertkrafael_net15:34 9 Apr '08  
GeneralRe: Inheritance? Pinmemberevolved7:03 11 Apr '08  
GeneralRe: Inheritance? PinmemberAnthony Missico9:22 10 Nov '08  
GeneralRepeater and late binding Pinmemberrippo20:33 8 Apr '08  
GeneralRe: Repeater and late binding PinmemberSam Rahimi5:00 9 Apr '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 9 Feb 2009
Editor: Deeksha Shenoy
Copyright 2008 by Sam Rahimi
Everything else Copyright © CodeProject, 1999-2009
Web22 | Advertise on the Code Project