Populating TextBox with Date via C#
Friday, August 22nd, 2008I have found through my web application development experience that it can be quite the pain if someone messes up a date. This is a huge headache for reporting purposes.
Methods to get around this can be one of many things. Validation for example simply forces the user to put in a date before they can submit information. Who is to say they are putting in the right date anyway? The ASP.NET calendar control is nice, as it gives a calendar and allows the user to pick a date. One method that I have found to work quite nicely for data that is entered for a day is to have the date set automatically.
What would be a scenario for this? The ideal setting is to track a date when an action is committed. Examples include form submission (no-brainer), requests, updates, etc.
For example, let’s say we have the following form:
<form runat="server"> <asp:Textbox ID="dateBox" runat="server"></asp:TextBox> </form>
Now, using the code behind file, we can write a simple line of code to send today’s date straight to the dateBox ASP Textbox upon the loading of the form.
With an aspx file, in the code-behind we can add an attribute to the Page_Load method to autopopulate a date (or set any value - same premise). Below we will set it within an IF statement for when the page posts back:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// This will happen upon a postback
dateBox.Text =DateTime.Today.ToString("MM/dd/yyyy");
}
Or you can set the value in outside of the PostBack IF statement:
dateBox.Text = DateTime.Today.ToString("MM/dd/yyyy");
As you can see, that simple line of code will send today’s date straight to the textbox without the user having to enter it. We have included it in the page load portion to see that it fires upon, as you guessed it, the loading of the page/form. To break it down further, we can add some pretty neat attributes to the code to produce other effects:
If we want to add tomorrow’s date, we can use .AddDays(+1)
DateTime.Today.AddDays(+1).ToString("MM/dd/yyyy");
If we want to add yesterday, we can use .AddDays(-1)
DateTime.Today.AddDays(-1).ToString("MM/dd/yyyy");
Want to populate a year? You can use the same premise. As Nico VanHaaster has pointed out, you can call the AddYears() method to combat leap year occurances:
DateTime.Today.AddYears(-1).ToString("MM/dd/yyyy");
As one can see, it’s a very simple approach to solving a problem with user’s entering a date and becoming frustrated if they have to do this more than once (such as they enter this data after each task on a given day).
Happy Programming!