Binding Objects to ASP.NET controls

May 8, 2004 | Uncategorized | 2 Comments

In web forms, I often bind objects that represent database tables to various ASP.NET control and then when the data is saved, I extract all the user-inputed data from the controls and send that data to the object.  Using reflection I’ve been able to automate the process quite a bit. The FormBinding object iterates through all the properties of an object, looks for ASP.NET controls with where the ID is equal to the property name (such as Document.Title and <asp:TextBox ID=”title” />) and then attempts to insert the object.property into the control.value.


The code can be used like this:

void Page_Load() {
if (!IsPostBack) {
    // Get an object from the datastore
    Document document = Document.GetDocument(1);
    // set the properties of the object to controls with the same ID
    FormBinding.BindObjectToControls(document,Page);
}



}
void SaveButton(Object sender, EventArgs e) {
   Document document = Document.GetDocument(1);
   // change the values of the properties of the object to values of controls on the page
   FormBinding.BindControlsToObject(document,Page);
   Documents.Save(document);

}

The FormBinding methods work with ListControls and controls with the following Properties (Value, Text, SelectedDate, and Checked) which covers a wide variety of controls including FreeTextBox.


Here’s the code.

2 responses to “Binding Objects to ASP.NET controls”

  1. Unresolvable says:

    WOW… new stuff that I didn’t know about… Well, guess who’s going to be coding alot less now :)

  2. pho3nix says:

    Please re-upload the code. Page not exist any more.

Leave a Reply

Hi, I'm John Dyer. In my day job, I build websites and create online seminary software for a seminary in Dallas. I also like to release open source tools including a pretty popular HTML5 video player and build tools that help people find best bible commentaries and do bible study. And just for fun, I also wrote a book on the theology of technology and media.

Fork me on GitHub

Social Widgets powered by AB-WebLog.com.