Properties In Pages and User Controls

Pages and User Controls often have to expose certain values that are actually a value stored in a control. For instance, a user control may have several controls that hold dollar amount data, date/time data, or other kinds. Oftentimes, data is loaded into a database and passed through some means to the user control. It's very helpful to use a property to represent the underlying data for that control. The reason is there is often some sort of conversion that takes place with the data. For instance, I was doing this with a user control:

public DateTime SubmittedDate { get { DateTime value; if (DateTime.TryParse(txtSubmittedDate.Text, value)) return value; else return new DateTime(1900, 1,1); } set { me.txtSubmittedDate.Text = value.ToString(); } }

This worked nice because the field was optional, and if it did, it defaulted to the smalldatetime equivalent of the date, which safely allowed it to be passed to a database. However, a change came in, and they wanted the time to be stripped off, so I could easily change the setter assignment using value.ToShortDateString(), and that made maintenance so much easier!

Even though this is a common approach for user controls, it could also be used for pages as well, and can have the same benefit. This works really well with amount fields, so you can do some processing, trim extra numeric characters after the decimal, etc.

Published Thursday, October 18, 2007 8:02 PM by bmains
Filed under:

Comments

No Comments

The leading UI suite for ASP.NET - Telerik radControls
Outstanding performance. Full ASP.NET AJAX support. Nearly codeless development.