Setting the value of insert parameter of SqlDataSource in codebehind

17,450

Solution 1

try this:

DateTime.Now.ToShortDateString(); 

"String or binary data would be truncated." usually has to do with fields in databases having a smaller size then what you're trying to put into it.

Solution 2

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())"  
Share:
17,450
Mahyar Kakaee
Author by

Mahyar Kakaee

Having fun programming?

Updated on June 05, 2022

Comments

  • Mahyar Kakaee
    Mahyar Kakaee almost 2 years

    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.