2

I am attempting to use the code-behind (Page_Load or PreRender) to set a date-time textbox in a DetailsView so that it defaults to a current date-time.

What I have attempted is (one of many variations):

protected void DetailsView2_PreRender(object sender, EventArgs e)
{
        ((TextBox)DetailsView2.FindControl("date_time")).Text = 
                  DateTime.Now.ToString("d");     
}

But all that I get is a 'NullReferenceException' error.

What I am doing wrong?

0

2 Answers 2

4

You can use detailsview controls DataBound event to set a value within your detailsview like that :

<asp:Label ID="DetailsView2" runat="server" OnDataBound="DetailsView2_DataBound">
</asp:Label>

Code Behind :

protected void DetailsView2_DataBound(object sender, EventArgs e)
{
    DetailsView myDetailsView = (DetailsView)sender;
    if(myDetailsView.CurrentMode == DetailsViewMode.Edit)
    {
        ((TextBox)myDetailsView.FindControl("date_time")).Text = DateTime.Now.ToString("d");     
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

To add to what Canavar suggested:

For use on a DetailsView assign like this:

<asp:DetailsView ID="DetailsView2" runat="server" AutoGenerateRows="False" 
    CellPadding="4" DataKeyNames="details_id" DataSourceID="SqlDataSource4" 
    DefaultMode="Insert" ForeColor="#333333" GridLines="None" Height="50px" 
    Width="125px" 
     AllowPaging="True"  OnPreRender="DetailsView2_DataBound">

And then in the code behind:

protected void DetailsView2_DataBound(object sender, EventArgs e)
{
    DetailsView myDetailsView = (DetailsView)sender;
    //Edit
    if (myDetailsView.CurrentMode == DetailsViewMode.Edit)
    {
        ((TextBox)myDetailsView.FindControl("TextBox2")).Text = DateTime.Now.ToString("g");
    }
    //Insert
    else if (myDetailsView.CurrentMode == DetailsViewMode.Insert)
    {
        ((TextBox)myDetailsView.FindControl("TextBox2")).Text = DateTime.Now.ToString("M/d/yyyy HH:mm");
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.