Wednesday, July 25, 2007

A simple way to handle data collection in email submission forms

Frequently I get asked to create a simple web-form that collects a few peices of information and either stores it or sends it to someone as an email - pretty straight forward... Where it gets annoying is when someone asks for a change and you end up messing with a bulk of string concatenation code.

A really simple solution to this problem is to place all of your controls in a panel, and then loop through the panel's controls collection and create a NameValueCollection with all of the questions/answers - which can then easily be stored or emailed off.

The code looks something like:


NameValueCollection answers = new NameValueCollection();

answers.Add("Date", DateTime.Now.ToString());

foreach(Control c in panelName.Controls)
{
switch(c.GetType().Name)
{
case "TextBox":
answers.Add(c.ID, ((TextBox)c).Text.Trim());
break;
case "DropDownList":
answers.Add(c.ID, ((DropDownList)c).SelectedValue);
break;
case "RadioButton":
answers.Add(c.ID, ((RadioButton)c).Checked.ToString());
break;
case "RadioButtonList":
answers.Add(c.ID, ((RadioButtonList)c).SelectedValue);
break;
}
}

FormMailer.SendResponses(answers);

No comments: