2012-06-02 161 views
1

設置的SqlDataSource的插入參數的值,我有這個SqlDataSource在我的形式:在代碼隱藏

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
     ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 

     InsertCommand="INSERT INTO [contact] ([Name], [phone], [email], [comment], [time]) VALUES (@Name, @phone, @email, @comment, @time)" 
     oninserting="SqlDataSource1_Inserting" > 
     <InsertParameters> 
      <asp:ControlParameter ControlID="TBname" Name="Name" PropertyName="Text" Type="String" /> 
      <asp:ControlParameter ControlID="TBphone" Name="phone" PropertyName="Text" Type="String" /> 
      <asp:ControlParameter ControlID="TBemail" Name="email" PropertyName="Text" Type="String" /> 
      <asp:ControlParameter ControlID="TBmessage" Name="comment" PropertyName="Text" Type="String" /> 
     </InsertParameters> 
    </asp:SqlDataSource> 

而且我有這個功能,必須保存前四個字段,並在第五當前時間文本框的值字段:

protected void SaveToDB(object sender, EventArgs e) 
{ 
     SqlDataSource1.InsertParameters["time"].DefaultValue = DateTime.Now.ToString(); 
     SqlDataSource1.Insert(); 
} 

4個字段從我的表單中的某些文本框中獲取它們的值。現在問題是最後一個字段:time,我無法設置它的值。當功能運行時,給你這個錯誤:

Exception Details: System.Data.SqlClient.SqlException: String or binary data would be truncated. The statement has been terminated.

我該怎麼辦?

感謝您抽出時間。

+0

DateTime.Now.ToShortDateString(); 試試這個 – Thousand

+0

@JaneDoe:是的!那會做。首先,請將您的評論寫爲答案,以便我可以選中它作爲答案。 在我的數據庫中的「時間」字段的類型是char(10),我把它作爲char(Max),現在很好。 謝謝, –

+0

完成!很高興我能幫忙^^ – Thousand

回答

1

試試這個: 「字符串或二進制數據將被截斷」

DateTime.Now.ToShortDateString(); 

通常與數據庫中具有較小大小的字段有關,然後嘗試將其放入其中。

+0

再次感謝男士。 –

3

您應該能夠直接在InsertCommand中使用SQL GetDate函數,而不使用代碼隱藏。

InsertCommand="INSERT INTO [contact] ([Name], [phone], [email], [comment], [time]) VALUES (@Name, @phone, @email, @comment, GetDate())"