user1954418
user1954418

Reputation: 1013

How to allow text with spaces in SQL from c# Textbox

I have this code that lets you input sentences in a textbox and it inserts in a table in SQL Server

using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
   con.Open();
   SqlCommand com = new SqlCommand("Insert Into tbl_notes (Notes,date_time) Values('" + txtbox_Notes.Text + "','" + DateTime.Now + "')", con);
   com.ExecuteNonQuery();
   txtbox_Notes.Text = "";
}

but when I press the button that calls this function, it gives out the Error

String or binary data would be truncated

Upvotes: 1

Views: 1122

Answers (2)

John Moore
John Moore

Reputation: 1331

You need to use parameters in your query, otherwise you are making it very error prone and also an easy hack for SQL injection.

Just try something like this and see if it work for you

using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
    {
        con.Open();
        SqlCommand com = new SqlCommand("Insert Into tbl_notes (Notes,date_time) Values(@Notes,@DateTime)", con);
        com.Parameters.Add(new SqlParameter("@Notes", txtbox_Notes.Text));
        com.Parameters.Add(new SqlParameter("@DateTime", DateTime.Now));
        com.ExecuteNonQuery();
        txtbox_Notes.Text = "";
    }

Upvotes: 0

juan.facorro
juan.facorro

Reputation: 9920

The error indicates that the length of the string you are trying to insert in the Notes column, is longer than the maximum allowed size in that column's definition. Try truncating the value for txtbox_Notes.Text to the specified column length.

I would also suggest you read a little bit about SQL Injection and take into account that the way you are executing this insertion command is really vulnerable to this kind of attacks. As suggested in a comment for the question, you could also use stored procedures to execute the insertion which not only provides a (thin) layer of security but also makes your code more readable.

Upvotes: 4

Related Questions