我正在尝试使用代码隐藏(Page_Load或PreRender)在DetailsView中设置日期时间文本框,以便默认为当前日期时间。
我所尝试的是(众多变体之一):
protected void DetailsView2_PreRender(object sender, EventArgs e)
{
((TextBox)DetailsView2.FindControl("date_time")).Text =
DateTime.Now.ToString("d");
}
但我得到的只是'NullReferenceException'错误。
我做错了什么?
答案 0 :(得分:4)
您可以使用detailsview控件DataBound事件在您的详细信息视图中设置一个值,如下所示:
<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)
添加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");
}
}