2009-06-25 78 views
2

我試圖使用代碼隱藏(Page_Load或PreRender)在DetailsView中設置日期時間文本框,以便它默認爲當前日期時間。ASP .NET - 設置DetailsView文本框的值

我試圖爲(許多變化之一):

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

但所有我得到的是一個「NullReferenceException異常」的錯誤。

我做錯了什麼?

回答

4

可以使用的DetailsView控件DataBound事件到您的DetailsView像內設置的值:

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

代碼背後:

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");  
    } 
} 
+1

+1 - 很好的答案 – 2009-06-25 19:09:29

1

要添加到什麼Canavar建議:

對於在DetailsView上使用像這樣分配:

<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"> 

然後在後面的代碼:

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"); 
    } 
}