Skip to content

Cory Foy

Organizational agility through intersecting business and technology

Menu
  • FASTER Fridays
  • Mapping Mondays
  • Player Embed
  • Search Videos
  • User Dashboard
  • User Videos
  • Video Category
  • Video Form
  • Video Tag
Menu

Binding ASP.NET Controls to QueryString parameters

Posted on May 18, 2005 by Cory Foy

I was flipping through Code Project today, and came across an article by Piers7 called Declarative QueryString Parameter Binding in ASP.NET. While I liked his approach, it required you to wrap all of your controls you wanted to bind with CustomAttributes.

I had to do something similar (probably we all have), but I don’t have the overhead of the custom attributes. Granted, I am only binding TextBoxes, but if that’s all you need, this works very well.

First, in my Page_Load, I check for PostBack listen for PreRender:


private void Page_Load(object sender, EventArgs e)
{
 if(!Page.IsPostBack)
 {
  this.PreRender +=
   new EventHandler(CommonMobilePage_PreRender);
 }
}

Now that we are in PreRender, we can call the method to check the controls. This will be a recursive call, since controls can hold other controls.


private void CommonMobilePage_PreRender(object sender, EventArgs e)
{
  BindControlsToURLRecursive(this.Controls);
}

Finally, we sprinkle a bit of reflection in to do the binding.


protected void BindControlsToURLRecursive(ControlCollection collection)
{
 foreach(Control control in collection)
 {
  if(control.GetType().Equals(typeof(System.Web.UI.MobileControls.TextBox)))
  {
   System.Web.UI.MobileControls.TextBox tb =
    (System.Web.UI.MobileControls.TextBox)control;

   //See if the field value is in the querystring
   if(Request.QueryString[control.ID] != null)
   {
    tb.Text = Request.QueryString[control.ID];
   }

  }

  if(control.HasControls())
  {
   BindControlsToURLRecursive(control.Controls);
  }
 }
}

Note that this is the code I use for my MobileControls, but the same concept would apply to WebControls.

© 2025 Cory Foy | Powered by Superbs Personal Blog theme