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

  • Today's agile organizations pose operations teams with a tremendous challenge: to deploy new releases to production immediately after development and testing is completed. To ensure that applications are deployed successfully, an automatic and transparent process is required. We refer to this process as Zero Touch Deployment™. This white paper reviews two approaches to Zero Touch Deployment--a script-based solution and a release automation platform. The article discusses how each can solve the key …

  • On-demand Event Event Date: December 18, 2014 The Internet of Things (IoT) incorporates physical devices into business processes using predictive analytics. While it relies heavily on existing Internet technologies, it differs by including physical devices, specialized protocols, physical analytics, and a unique partner network. To capture the real business value of IoT, the industry must move beyond customized projects to general patterns and platforms. Check out this webcast and join industry experts as …

Most Popular Programming Stories

More for Developers

RSS Feeds