Setting the value of insert parameter of SqlDataSource in codebehind

Mahyar Kakaee picture Mahyar Kakaee · Jun 2, 2012 · Viewed 17.2k times · Source

I have this SqlDataSource in my form:

<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>

And I have this function which has to save the values of TextBoxes in first four fields and current time in fifth field:

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

4 of 5 fields get their values from some TextBoxes in my form. now problem is the last field: time which I can't set it's value. When the function runs, gives you this error:

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

What should I do?

thank you for taking time.

Answer

Dave picture Dave · Sep 25, 2012

You should be able to use the SQL GetDate function directly in the InsertCommand without using code-behind.

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