Setting Form Values Automatically with SubSonic

Tedious coding sucks. SubSonic saves lots of time. But I want it to save me more. So I've started working on a method that will fill out the controls for me so I don't have to. It's simple really. I just new() up a the model I will use and pass it to my method along with the UserControl I have my form elements in.

   1:  public void SetupForm<T>(Control form, T activeRecord ) 
   2:      where T : AbstractRecord<T> ,new()
   3:  {
   4:      TableSchema.TableColumnSettingCollection settings = activeRecord.GetColumnSettings();
   5:      foreach (TableSchema.TableColumnSetting setting in settings)
   6:      {
   7:          Control settingControl = form.FindControl(setting.ColumnName);
   8:          if (settingControl is TextBox)
   9:              ((TextBox)settingControl).Text = 
  10:                  activeRecord.GetColumnValue<string>(setting.ColumnName);
  11:          if (settingControl is DropDownList)
  12:              ((DropDownList)settingControl).SelectedValue = 
  13:                  activeRecord.GetColumnValue<string>(setting.ColumnName);
  14:      }
  15:  }

The key thing is to make sure you have called EnsureChildControls() before calling this method.

So in my control the code looks like

   1:  int issueId = SubSonic.Sugar.Web.QueryString<int>("issue");
   2:  if (issueId != 0)
   3:  {
   4:      EnsureChildControls();
   5:      Issue issue = new Issue(issueId);
   6:      //BasePage inherits from System.Web.UI.Page
   7:      BasePage.SetupForm(this, issue);
   8:  } 

Now this is pretty rough and more than anything a proof of concept so your mileage may vary. But I figure this is a good place to start

kick it on DotNetKicks.com

4 Comments

  • Keep it up.. Curious where this might end :-)
    I work with subsonic too and must say it is a breeze to work with. But the kind of things you do makes it even better..

    Keep me posted

  • Very cool. This is like the opposite of the LoadFromPost method.

  • great start. I'm interested in how this progresses as well.

    it gets difficult once the user customizes the control. one user may use a composite control with dropdowns for Day, month, Year and another may use a DHTML calendar control with a textbox for the datetime.

    you're code will either have to allow for configuring these complexities or just offer one solution...ala scaffolding - it gets your started, and is great for high level design stuff...but once it gets down to the nitty gritty the developer will have to migrate away from your solution and onto their own.

    which isn't a bad thing.

    but I like your thinking.


  • go for ITextControl for text controls, e.g.:

    ...
    if (settingControl is System.Web.UI.ITextControl)
    ...

Comments have been disabled for this content.