Complex Repeater and DataList Controls Made Simple
page 1 of 1
Published: 28 Apr 2006
Unedited - Community Contributed
Abstract
In this article, Michael demonstrates how to create a simple list control that employs User Controls to encapsulate edit capability, event handling, and complex code.
by Michael Libby
Feedback
Average Rating: 
Views (Total / Last 10 Days): 8412/ 25

Step By Step Instructions

The Web Application

Create a new Visual C# ASP.NET Web Site named DataListUserCtrl.

The Business Object

1.      Add a business object that will store the data used by the list control.  Right click on the project in Solution Explorer, select Add and then select class with the name, Contacts.cs.  Enter the following business object class definition.

Listing 1 - The Business Object

[Serializable]
public class Contact
{
  private string name = string.Empty;
  private string phone = string.Empty;
  private string callback = "Now";
  public string Name
  {
    get
    {
      return name;
    }
    set
    {
      name = value;
    }
  }
  public string Phone
  {
    get
    {
      return phone;
    }
    set
    {
      phone = value;
    }
  }
  public string Callback
  {
    get
    {
      return callback;
    }
    set
    {
      callback = value;
    }
  }
}

Note: Marking a class as [Serializable] allows it to be serialized to ViewState.

The Web User Control

1.      Add a Web User Control that will encapsulate code which edits and displays the business object.  Right click on the project and select Add.  Then Add the Web User Control with the name ContactUC.ascx. 

2.      Place a button (id=btnDelete), two TextBox controls (id=tbName, and id=tbPhone) and a DropDown (id=ddlCallback) on the ContactUC Form.  Change the ddlCallback property AutoPostBack="True" and the items collection to Now, Today, Tomorrow and Next Week.  Change the btnDelete CommandName property to Delete.  Finally, arrange the form to look like Image 1. 

3.      While editing the form in design mode, double click on the delete button and the ddlCallback dropdown to create event handlers.  Enter the following code for the event handlers:

Listing 2 - Event Handlers

private void btnDelete_Click(object sender,System.EventArgs e)
{
  RaiseBubbleEvent(sender, e);
}
 
private voidddlCallback_SelectedIndexChanged(object sender, System.EventArgs e)
{
  Controls.Add(new LiteralControl("Youselected " + ddlCallback.SelectedValue));
}

The btnDelete_Click event handler is optional.  However, if it is included then its event must be bubbled to the parent page.  The ddlCallback_SelectedIndexChanged demonstrates how the Web User control handles autopostback events.

4.      Add a UserControlData property that will allow the DataList to pass a business object into the User Control whenever its Bind() method is called.  This will be covered later when we discuss how to add the DataList to the ASPX page.

Listing 3 - UserControlData Property

Private Contact contact;
public Object UserControlData
{
  set
  {
    contact = (Contact)value;
  }
  get
  {
    return contact;
  }
}

5.      Override the User Control's Bind method that sets the form's variable from the business object by doing the following.

Listing 4 - Overriding DataBind

public override void DataBind()
{
  base.DataBind();
  tbName.Text = contact.Name;
  tbPhone.Text = contact.Phone;
 ddlCallback.Items.FindByValue(contact.Callback).Selected = true;
}

Note: The base.DataBind forces the UserControlData property to be initialized.

6.      Add a method that allows the UserControl to save state back to the business object, as seen in listing 5.

Listing 5 - Saving State

public void SaveState(Contact contact)
{
  contact.Name = tbName.Text;
  contact.Phone = tbPhone.Text;
  contact.Callback = ddlCallback.SelectedValue;
}

The WebForm and DataList Control

1.      Right-click on the project in Solution Explorer, select Add New Item, and then select the Web Form named ContactsDataListPg.aspx.

2.      Place a DataList (id = dlContacts) and a button (id = btnAdd) on the WebForm.  Right click on the DataList and select Edit Template and then select Item Templates.  Drag the Web User Control, ContactUC (id = ContactUC1), into the ItemTemplate.  Switch to the HTML view and add the UserControlData property set to "<%# Container.DataItem %>".  For example:

Listing 6 - Adding ContactUC to the WebForm

<uc1:ContactUC id=ContactUC1 runat="server"UserControlData="<%# Container.DataItem %>">

3.      Switch to the design view and add the ItemCommand event handler to dlContacts and then double click on the btnAdd.  Enter the following code for the event handlers.

Listing 7 - Event Handlers

private void btnAdd_Click(object sender,System.EventArgs e)
{
  Contacts.Add(new Contact());
  dlContacts.DataSource = Contacts;
  dlContacts.DataBind();
}
 
private void dlContacts_ItemCommand(object source,
 System.Web.UI.WebControls.DataListCommandEventArgs e)
{
  if (e.CommandName == "Delete")
  {
    Contacts.RemoveAt(e.Item.ItemIndex);
    dlContacts.DataSource = Contacts;
    dlContacts.DataBind();
  }
}

Note: ItemCommand is called when any button in the DataList is pressed.  The delete button is handled in the User Control but also bubbled so that it can be handled here, where the Contact object can be deleted from the Contacts collection.

4.      Add a property called Contacts which persists a collection of Contact objects in ViewState.  Enter the following code:

Listing 8 - Persisting a List of Business Objects

private IList Contacts
{
  get
  {
    return(ArrayList)ViewState["Contacts"];
  }
  set
  {
    ViewState["Contacts"= value;
  }
}

5.      Add code in the Page_Load to either initialize or save the User Control state.

Listing 9 - Loading State into Business Objects and Web User Controls

if (!Page.IsPostBack)
{
  Contacts = new ArrayList();
  dlContacts.DataSource = Contacts;
  dlContacts.DataBind();
}
 
else
{
  foreach (DataListItem item indlContacts.Items)
  {
    ContactUC uc =(ContactUC)item.FindControl("ContactUC1");
   uc.SaveState((Contact)Contacts[item.ItemIndex]);
  }
}

Run the Web Application

Build and run the Web Application.  Press the Add button to add names to the DataList.  Select "call" from the dropdown to see how the user control is able to handle select events.  The final output will be as shown in the figure given below.  Press the delete button to delete a row from the DataList.

Figure 1

Download Sample

[Download Sample]

Conclusion

Now that you are able to encapsulate a business object, event handlers and complex code inside of a Web User control, the DataList code becomes much simpler.  The DataList code can focus on maintaining the collection of business objects.  If you had any difficulty following these instructions then please download and run the example project.  The download also contains a Repeater example.



User Comments

Title: Wish I had found this TWO WEEKS ago !!   
Name: ron m
Date: 2009-08-25 5:23:49 PM
Comment:
Man... I **so** wish I had found this sooner. I've been struggling with doing this EXACT thing that entire time. I think the "bosses" were getting a little impatient with me. Anyway, I have a user control that's WAY more complicated than this, and now it's working flawlessly. You are the MAN!
Title: great sample   
Name: singh
Date: 2009-08-14 3:49:12 PM
Comment:
I really liked this sample its great.Thanks
Title: great sample   
Name: peter
Date: 2009-08-07 9:04:28 AM
Comment:
I hava a repeater in a repeater how can i get de value of a textbox?
Title: Adding sub headers to a repeater control   
Name: neha
Date: 2008-10-22 1:47:18 PM
Comment:
Hi,

i am trying to add a subheading to each category of items.
I tried it but..but i can do it on grid but not in a repeater .Bcoz of someother reasons i am forced to use a repeater control

. Please any one help me to this
Title: Thanks   
Name: Kunal
Date: 2007-09-16 1:51:56 PM
Comment:
It helps me a lot.
Title: Thanks a lot   
Name: Joshua
Date: 2007-07-25 2:22:49 PM
Comment:
Your article really simplified a difficult process.

Thanks!
Title: thank you Michael Libby!   
Name: Rodney Vinyard
Date: 2007-04-03 1:01:02 PM
Comment:
thank you Michael Libby!
Title: Works Great!   
Name: Jenny McRoe
Date: 2006-05-05 3:47:01 PM
Comment:
I was able to easily implement event handling in a complex datalist. Thanks!

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-10-09 3:56:23 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search