If you are using C#3 you can use LINQ and extension methods to achieve this in a very nice way. First you need to create an extension method devised by Bryan Watts in this thread:
public static IEnumerable<KeyValuePair<string, string>> ToPairs(this NameValueCollection collection)
{
if (collection == null)
{
throw new ArgumentNullException("collection");
}
return collection.Cast<string>().Select(key => new KeyValuePair<string, string>(key, collection[key]));
}
Now, say you had a form like this:
<form id="form1" runat="server">
<div>
<input type="text" name="XXX_Name" value="Harold Pinter" />
<input type="text" name="XXX_Email" value="harold@example.com" />
<input type="text" name="XXX_Phone" value="1234 5454 5454" />
<input type="text" name="YYY_Name" value="AN. Other" />
<input type="text" name="YYY_Email" value="another@example.com" />
<input type="text" name="YYY_Phone" value="8383 3434 3434" />
<input type="submit" value="submit button" />
</div>
</form>
You could do this in your codebehind:
protected void Page_Load(object sender, EventArgs e)
{
var data = Request.Form.ToPairs().Where(k => k.Key.StartsWith("XXX_"));
foreach (var item in data)
{
Response.Write(String.Format("{0} = '{1}', ", item.Key, item.Value));
}
}
Which would output:
XXX_Name = 'Harold Pinter'
XXX_Email = 'harold@example.com'
XXX_Phone = '1234 5454 5454'