Thursday, June 17, 2010

Code: Create Properties for ASP.Net Web Form Pages

When developing web form pages I like to create properties to interact with user input controls that are more complex than simple strings (Enums, DateTime, etc).  This allows me to keep more of my page strongly typed.

using System;

namespace WebFormsSamples
{
public partial class PageProperties : System.Web.UI.Page
{
public enum PrimaryColors
{
Red,
Blue,
Yellow
}

public PrimaryColors SelectedColor
{
get
{
PrimaryColors result;
Enum.TryParse<PrimaryColors>(ColorInput.SelectedValue, out result);
return result;
}
set
{
ColorInput.SelectedValue = value.ToString();
}
}

public DateTime SelectedDate
{
get
{
DateTime result = DateTime.MinValue;
DateTime.TryParse(DateInput.Text, out result);
return result;
}
set
{
DateInput.Text = value.ToShortDateString();
}
}

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindControls();
SelectedColor = PrimaryColors.Yellow;
SelectedDate = DateTime.Today;
}
}

/// <summary>
///
Notice the strong types here!
/// </summary>
protected void SaveInput_Click(object sender, EventArgs e)
{
SaveItem(SelectedColor, SelectedDate);
}

private void BindControls()
{
ColorInput.DataSource = Enum.GetNames(typeof(PrimaryColors));
ColorInput.DataBind();
}

private void SaveItem(PrimaryColors color, DateTime date)
{
lblResult.Text = SelectedColor.ToString() + " " + date.ToLongDateString();
}
}
}