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

  • On-demand Event Event Date: September 10, 2014 Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild." This loop of continuous delivery and continuous feedback is how the best mobile …

  • It's hardly surprising that half of small businesses fail within the first 1-5 years. It's not easy to launch a new product, single-handedly manage everything from IT to accounting, fend off the competition, and grow a customer base – all at the same time – even with a great concept. Offering awesome customer service can make the difference between a startup that flies and a startup that dies. Read this white paper to learn nine ways customer support can help you beat the competition and grow your …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds