3 Dec
2004

Parsing Page Parameters in ASP.Net

This will be obvious to most, but I am slow to catch up to the rest
of you. 

Are you tired of writing parameter validation code in your ASP.Net pages? Usually
it looks something like this:

1protected override void OnLoad(EventArgs
e)
2{
3   if(
!this.IsPostBack )
4  
{
5      
projName = this.ParseRequiredParam(“p”);
6       if(
projName == null || projName.Lentgh < 1)
7          throw new ArgumentNullException( “p”, “You
must pass a project name.” );
8  
}
9}

Instead, place this function in your page’s base class:

1protected string ParseRequiredParam( string paramName
) 

2{
3 string value = this.Request.Params[ paramName ];
4 if( value == null || value.Length < 1 )
5 {
6 throw new ArgumentNullException( paramName, "Parameter is required.");
7 }
8 return value;
9}
And simply call it from within
your code like this: 
1protected override void OnLoad(EventArgs
e) 

2{
3 if(
!this.IsPostBack ) 
4 { 
5 projName
= this.ParseRequiredParam("p"); 
6 } 
7} 
Enjoy.