AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=811&pId=-1
Complex Repeater and DataList Controls Made Simple
page
by Michael Libby
Feedback
Average Rating: 
Views (Total / Last 10 Days): 8693/ 9

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.


Product Spotlight
Product Spotlight 

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