2014-04-10 50 views
1

我正在使用DetailView通過sqlDataSource將數據插入到GridView中。我試圖將DetailView的一個字段設置爲頁面加載的當前日期/時間,以便用戶不必輸入日期/時間。我沒有收到任何錯誤 - 但是,DetailView的「更新日期」字段無法顯示當前的日期/時間。將當前日期設置爲DetailView的TemplateField

這是我的超文本:

<asp:DetailsView 
     id="dtlShipModes" 
     DataSourceID="SqlDataSource1" 
     AutoGenerateRows="False" 
     DefaultMode="Insert" 
     Runat="server" BackColor="White" BorderColor="White" BorderStyle="Ridge" 
     BorderWidth="2px" CellPadding="3" CellSpacing="1" GridLines="None"> 
     <EditRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" /> 
     <Fields> 
     <asp:BoundField 
      DataField="ShipMode" 
      HeaderText="Ship Mode:" /> 
       <asp:CheckBoxField 
      DataField="Active" 
      HeaderText="Active:" /> 
      <asp:TemplateField HeaderText="Update Date:"> 
       <EditItemTemplate> 
        <asp:TextBox ID="txtUpdateDate" runat="server" Text='<%# Bind("UpdateDate") %>'></asp:TextBox> 
       </EditItemTemplate> 
       <InsertItemTemplate> 
        <asp:TextBox ID="txtUpdateDate" runat="server" Text='<%# Bind("UpdateDate") %>'></asp:TextBox> 
       </InsertItemTemplate> 
       <ItemTemplate> 
        <asp:Label ID="Label1" runat="server" Text='<%# Bind("UpdateDate") %>'></asp:Label> 
       </ItemTemplate> 
      </asp:TemplateField> 
      <asp:BoundField 
      DataField="UpdateBY" 
      HeaderText="Update BY:" /> 

      <asp:CommandField ShowInsertButton="true" InsertText="Add" /> 

     </Fields> 
     <FooterStyle BackColor="#C6C3C6" ForeColor="Black" /> 
     <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" /> 
     <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" /> 
     <RowStyle BackColor="#DEDFDE" ForeColor="Black" /> 
    </asp:DetailsView> 

這是後面的代碼:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 

     Dim txtupdatedby As String = DirectCast(dtlShipModes.FindControl("txtUpdateDate"), TextBox).Text 
     txtupdatedby = DateTime.Now.ToString 
    End Sub 

我能得到一些幫助,請爲我在做什麼錯?

回答

0

要擴大Mych's answer一點,你想處理DetailsView控件的ItemCreated事件:

<asp:DetailsView 
    id="dtlShipModes" 
    DataSourceID="SqlDataSource1" 
    AutoGenerateRows="False" 
    DefaultMode="Insert" 
    ItemCreated="dtlShipModes_ItemCreated" 
    Runat="server" BackColor="White" BorderColor="White" BorderStyle="Ridge" 
    BorderWidth="2px" CellPadding="3" CellSpacing="1" GridLines="None"> 

然後寫這樣的事件處理程序:

protected void dtlShipModes_ItemCreated(Object sender, EventArgs e) 
{ 
    Dim txtupdatedby As TextBox = DirectCast(dtlShipModes.FindControl("txtUpdateDate"), TextBox) 
    txtupdatedby.Text = DateTime.Now.ToString 
} 

請注意,我稍微改變了您的實現,以使用對Text的引用盒子,而不是字符串。

這是所有必要的,因爲DetailsView未在頁面的Load事件中加載數據。

+1

謝謝你的解釋和例子,一切順利 – user1724708

+0

@ user1724708不客氣!我很高興我能幫忙=) – jadarnel27

相關問題