Tuesday, December 28, 2010

Pre-populate ReadOnly TextBox in a FormView with current date and time

I had to pre-populate a FormView that contains a textbox with the current date and time.

Googled and found this link which proved to be quite useful, though not exactly what I wanted.

Pre-populate DetailsView InsertItemTemplate TextBox with User.Identity.Name value - ASP.NET Forums


Anyway, what you need to do is to first add an event handler for "ondatabound" in the FormView.
Assuming you have a textbox named "TextBoxDataOfEntry" in the InsertItemTemplate of the FormView, this is how I got the current date and time to be populated in the textbox.

protected void FormView1_DataBound(object sender, EventArgs e)
if (FormView1.CurrentMode == FormViewMode.Insert)
DateTime datetime = DateTime.Today;
TextBox tbDateOfEntry = (TextBox)FormView1.FindControl("TextBoxDateOfEntry");
tbDateOfEntry.Text = datetime.ToString();
}//end FormView1_DataBound

No comments: