Skip to main content
 首页 » 编程设计

c#之在codebehind中设置SqlDataSource的insert参数的值

2024年02月20日12落叶无声

我的表单中有这个 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(); 
} 

5 个字段中的 4 个从我表单中的一些文本框获取它们的值。现在的问题是最后一个字段:time 我无法设置它的值。当函数运行时,给你这个错误:

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

我该怎么办?

感谢您抽出时间。

请您参考如下方法:

您应该能够直接在 InsertCommand 中使用 SQL GetDate 函数,而无需使用代码隐藏。

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