ASP.NET Tip: Binding to Alternate Data Sources

Two of the controls introduced with .NET were the validation control and the validation summary control. I do a lot of server-side validation and I liked the concept of the validation summary, where all the errors on the form are shown at once. JavaScript nag windows annoy me when they validate one field at a time. The classes I generally use create a list of errors in a string format. However, this tip shows you how to create an ArrayList of an ErrorMessage class that can be bound to a Repeater, providing the same effect as the ValidationSummary.

Although .NET developers spend a lot of time talking about binding database-related objects to grids and repeaters, they don't talk much about binding their own objects to grids and lists. This can come in handy in many instances. This tip shows how to build a class that can be bound to a Repeater without involving any databases.

Let's start with a simple class that holds your error message:

public class ValidationError
{
   private string _error;

   public string ErrorMessage
   {
      get { return _error; }
      set { _error = value; }
   }

   public ValidationError(string errorMessage)
   {
      ErrorMessage = errorMessage;
   }
}

The Eval function used in conjunction with data binding will work only with properties, not public variables. That's why the property is defined. The class also has a constructor that takes the error message, which makes it easier to instantiate and populate the object in one statement.

Next, let's add a typical data entry form to enter information about a user. Any data entry form will work, and this form leaves off the extra HTML for clarity:

<form id="form1" runat="server">
   <asp:Repeater ID="rptErrors" runat="server" Visible="False">
      <HeaderTemplate>
         Please correct these errors:
         <ul>
      </HeaderTemplate>
      <ItemTemplate>
         <li><%# Eval("ErrorMessage") %></li>
      </ItemTemplate>
      <FooterTemplate>
         </ul>
      </FooterTemplate>
   </asp:Repeater>
   <table cellspacing="0" cellpadding="3" border="0">
      <tr class="boldtext">
         <td>First Name:</td>
         <td><asp:TextBox ID="txtFirstName" CssClass="text"
                          runat="server" Width="200"
                          MaxLength="40" /></td>
      </tr>
      <tr class="boldtext">
         <td>Last Name:</td>
         <td><asp:TextBox ID="txtLastName" CssClass="text"
                          runat="server" Width="200"
                          MaxLength="40" /></td>
      </tr>
      <tr>
         <td colspan="2" align="center">
            <asp:LinkButton ID="btnSave"
                            runat="server"
                            CssClass="boldtext">Save</asp:LinkButton>
         </td>
      </tr>
   </table>
</form>

The Repeater control at the top will build an unordered/bulleted list of your errors. A couple of entry boxes and a submit LinkButton round out the form. The following is the code behind:

public partial class SamplePage : System.Web.UI.Page
{
   protected override void OnInit(EventArgs e)
   {
      base.OnInit(e);
      btnSave.Click += new EventHandler(btnSave_Click);
   }

   protected void Page_Load(object sender, EventArgs e)
   {
      if (!Page.IsPostBack)
      rptErrors.Visible = false;

   }

   void btnSave_Click(object sender, EventArgs e)
   {
      ArrayList errors = new ArrayList();
      if (txtFirstName.Text == "")
         errors.Add(new ValidationError("First name is required."));

      if (txtLastName.Text == "")
         errors.Add(new ValidationError("Last name is required."));

      if (errors.Count > 0)
      {
         rptErrors.DataSource = errors;
         rptErrors.DataBind();
         rptErrors.Visible = true;
      }
      else
      {
         // do save logic here and move to next page
      }
   }
}

You add an event handler for the LinkButton and initially hide the Repeater, since there won't be any errors when the form first loads. When the user hits the Save button, the form validates the two fields and adds the ValidationError objects to the ArrayList. When it's done validating, it checks for errors and if any are found, binds those to the Repeater. The Eval function in the Repeater (ASPX code) looks for the ErrorMessage property and displays the text in the list.

You can use this technique with any of your objects, regardless of function. The key is to create actual properties for any values you want to display.

About the Author

Eric Smith is the owner of Northstar Computer Systems, a Web-hosting company based in Indianapolis, Indiana. He is also a MCT and MCSD who has been developing with .NET since 2001. In addition, he has written or contributed to 12 books covering .NET, ASP, and Visual Basic. Send him your questions and feedback via e-mail at questions@techniquescentral.com.



Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: September 17, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Another day, another end-of-support deadline. You've heard enough about the hazards of not migrating to Windows Server 2008 or 2012. What you may not know is that there's plenty in it for you and your business, like increased automation and performance, time-saving technical features, and a lower total cost of ownership. Check out this upcoming eSeminar and join Rich Holmes, Pomeroy's practice director of virtualization, as he discusses the …

  • The explosion in mobile devices and applications has generated a great deal of interest in APIs. Today's businesses are under increased pressure to make it easy to build apps, supply tools to help developers work more quickly, and deploy operational analytics so they can track users, developers, application performance, and more. Apigee Edge provides comprehensive API delivery tools and both operational and business-level analytics in an integrated platform. It is available as on-premise software or through …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds