Useful Code Snippet: Web Property

Write WebControls much? Well, I do and I have a code snippet that I pretty much can’t live without. It is used for creating ViewState backed properties. Here is the basic pattern I use when creating properties for my web controls:

public string Name
{
    get
    {
        object o = ViewState["Name"];
        return o == null ? String.Empty : (string)o;
    }
    set { ViewState["Name"] = value; }
}

Basically, you just want a property (in this case a string named “Name”) and you want to store it in ViewState. And when the value is being retrieved, if it is not in ViewState, you want to retrieve some default value. This is a pattern that I repeat over and over in my controls. So I made a code snippet to make it easier.

I use the shortcut ‘webprop’

image

and it expands like this:

image

To install, you just need to place the .snippet file (link to download below) in your ‘My Snippets’ folder which in windows vista is located at:

C:\Users\<UserName>\Documents\Visual Studio 2005\Code Snippets\Visual C#\My Code Snippets

or if you use Visual Studio 2008:

C:\Users\<UserName>\Documents\Visual Studio 2008\Code Snippets\Visual C#\My Code Snippets

I hope this is helpful. It saves me a bunch of time.

You can download the .snipped file here

kick it on DotNetKicks.com

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: