在代码隐藏中设置 Sql数据源的插入参数的值
本文关键字:插入 参数 数据源 Sql 代码 隐藏 设置 | 更新日期: 2023-09-27 18:36:01
我的表格中有这个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
我无法设置它的值。当函数运行时,会给出此错误:
异常详细信息:System.Data.SqlClient.SqlException:字符串或 二进制数据将被截断。该语句已终止。
我该怎么办?
感谢您抽出宝贵时间。
您应该能够直接在 InsertCommand 中使用 SQL GetDate 函数,而无需使用代码隐藏。
InsertCommand="INSERT INTO [contact] ([Name], [phone], [email], [comment], [time]) VALUES (@Name, @phone, @email, @comment, GetDate())"
试试这个:
DateTime.Now.ToShortDateString();
"字符串或二进制数据将被截断"通常与数据库中的字段大小小于您尝试放入其中的字段有关。