String or binary data would be truncated.

Jasonkwp

New member
Joined
Jun 16, 2019
Messages
4
Programming Experience
Beginner
Hi i am new to ASP.NET C# and i am trying to write a simple inventory system , however i receive the following error when i debug the code for errors.

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


Please be advise that i do know what the error means but i have checked my SQL db table design and the character lengths for each field are set high enough to cater for the text to be entered. see db table design in screenshot below
546


Here is my C# code:

C#:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using System.Security.Cryptography;

namespace InformationTechnologyInventoryStock
{
    public partial class Workstations : Form
    {
        private int n;

        public Workstations()
        {
            InitializeComponent();
        }

        private void Workstations_Load(object sender, EventArgs e)

        {
            using (SqlConnection con = new SqlConnection())
            {
                con.ConnectionString = (@"Data Source=SH-JASONK\DEV;Initial Catalog=StockInventory;Integrated Security=True");
                con.Open();
                bool status = false;
                if (combostatus.SelectedIndex == 0)
                {
                    status = true;
                }
                else
                {
                    status = false;
                }
                using (SqlCommand cmd = con.CreateCommand())
                {
                    cmd.CommandText =
                    cmd.CommandText = (@"INSERT INTO [StockInventory].[dbo].[Workstations](Emp_Name,
Emp_Surname, Department, Company,
Hostname, Wkst_Status, Make, Model, SerialNumber,
ProductNumber, PurchaseDate, ExpiryDate, Memory,
Processor, HDD, OS, MSOffice) VALUES ('" + txtname.Text + "','" + txtsurname.Text + "','" + combodept.Text + "','" + combocompany.Text + "','" + txthostname.Text + "','" + combostatus.Text + "','" + combomake.Text + "','" + txtmodel.Text + "','" + textsn.Text + "','" + txtprodnum.Text + "','" + dateTimePicker1.Value.ToString("yyyy/MM/dd") + "','" + dateTimePicker2.Value.ToString("yyyy/MM/dd") + "','" + combomem + "','" + txtproc + "','" + combohdd + "','" + comboOS + "','" + combooffice + "')");
                    cmd.ExecuteNonQuery();
                    con.Close();

                    //Reading Data:

                    SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM [StockInventory].[dbo].[Workstations] ", con);
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    dataGridView1.Rows.Clear();
                    foreach (DataRow item in dt.Rows)
                    {
                        int n = dataGridView1.Rows.Add();
                        dataGridView1.Rows[n].Cells[0].Value = item["Emp_Name"].ToString();
                        dataGridView1.Rows[n].Cells[1].Value = item["Emp_Surname"].ToString();
                        dataGridView1.Rows[n].Cells[2].Value = item["Department"].ToString();
                        dataGridView1.Rows[n].Cells[3].Value = item["Company"].ToString();
                        dataGridView1.Rows[n].Cells[4].Value = item["Hostname"].ToString();
                        if ((bool)item["Wkst_Status"])
                            if (combostatus.SelectedIndex == 0)
                            {
                                dataGridView1.Rows[n].Cells[5].Value = "ACTIVE";
                            }
                            else
                            {
                                dataGridView1.Rows[n].Cells[5].Value = "INACTIVE";
                            }

                        dataGridView1.Rows[n].Cells[5].Value = item["Make"].ToString();
                        dataGridView1.Rows[n].Cells[6].Value = item["Model"].ToString();
                        dataGridView1.Rows[n].Cells[7].Value = item["SerialNumber"].ToString();
                        dataGridView1.Rows[n].Cells[8].Value = item["ProductNumber"].ToString();
                        dataGridView1.Rows[n].Cells[9].Value = item["PurchaseDate"].ToString();
                        dataGridView1.Rows[n].Cells[10].Value = item["ExpiryDate"].ToString();
                        dataGridView1.Rows[n].Cells[11].Value = item["Memory"].ToString();
                        dataGridView1.Rows[n].Cells[12].Value = item["Processor"].ToString();
                        dataGridView1.Rows[n].Cells[13].Value = item["HDD"].ToString();
                        dataGridView1.Rows[n].Cells[14].Value = item["OS"].ToString();
                        dataGridView1.Rows[n].Cells[15].Value = item["MSOffice"].ToString();
                    }

                    MessageBox.Show("INSERTED SUCCESSFULLY");
                }
            }
        }
    }
}

Can you please advise what i am doing wrong or where to search for the issue

thank you in advance

Jason
 
Last edited by a moderator:
Can you please edit your post and use the code tags insert button. That will make your formatting as it is in your IDE which makes it easier for us to read.
 
Note quote it. Put it within code tags.

Anyway as an aside,
C#:
cmd.CommandText = (@"INSERT INTO [StockInventory].[dbo].[Workstations](Emp_Name,
Emp_Surname, Department, Company,
Hostname, Wkst_Status, Make, Model, SerialNumber,
ProductNumber, PurchaseDate, ExpiryDate, Memory,
Processor, HDD, OS, MSOffice) VALUES ('" + txtname.Text + "','" + txtsurname.Text + "','" + combodept.Text + "','" + combocompany.Text + "','" + txthostname.Text + "','" + combostatus.Text + "','" + combomake.Text + "','" + txtmodel.Text + "','" + textsn.Text + "','" + txtprodnum.Text + "','" + dateTimePicker1.Value.ToString("yyyy/MM/dd") + "','" + dateTimePicker2.Value.ToString("yyyy/MM/dd") + "','" + combomem + "','" + txtproc + "','" + combohdd + "','" + comboOS + "','" + combooffice + "')");
This is a great way to open yourself up for SQL injection attack.

See:
exploits_of_a_mom.png
 
do you want me to quote the entire code
The editor that you posted the code in has a toolbar. I'm sure that you've used such things before. Please explore it and see what it can do. I've done it for you this time. Please make sure that you ALWAYS include the original indenting in your code snippets too. I had to copy and paste your code into VS to reinstate the indenting. That's the most important thing in making code readable, but the syntax highlighting helps too.

Also, don;t just copy and paste every line of code you have and expect us to trawl through to find the relevant part. It's your responsibility to focus on the relevant part and only post that. For instance, did you copy that error message into a search engine to find information about it? It would be fairly easy to find an explanation of the reason from that. Even if that doesn't lead you to a final solution, it means that you can only provide us with the information and code that is relevant to the problem.

Basically, the error message is telling you that you're trying to save a value that is longer than the max size specified in the database, e.g. trying to save 51 characters to a column declared as type varchar(50). It's up to you to validate data before trying to save it and max lengths are one of the things you need to check, especially if your UI doesn't enforce such things.

Also, as suggested, you really need to learn how to use parameters. As it stands, a malicious user could delete everything in your database and possibly event the database itself. Try this:

 
The editor that you posted the code in has a toolbar. I'm sure that you've used such things before. Please explore it and see what it can do. I've done it for you this time. Please make sure that you ALWAYS include the original indenting in your code snippets too. I had to copy and paste your code into VS to reinstate the indenting. That's the most important thing in making code readable, but the syntax highlighting helps too.

Also, don;t just copy and paste every line of code you have and expect us to trawl through to find the relevant part. It's your responsibility to focus on the relevant part and only post that. For instance, did you copy that error message into a search engine to find information about it? It would be fairly easy to find an explanation of the reason from that. Even if that doesn't lead you to a final solution, it means that you can only provide us with the information and code that is relevant to the problem.

Basically, the error message is telling you that you're trying to save a value that is longer than the max size specified in the database, e.g. trying to save 51 characters to a column declared as type varchar(50). It's up to you to validate data before trying to save it and max lengths are one of the things you need to check, especially if your UI doesn't enforce such things.

Also, as suggested, you really need to learn how to use parameters. As it stands, a malicious user could delete everything in your database and possibly event the database itself. Try this:

i have searched for the error and a possible solution , i have also checked the max length of the db table and UI
 
i have also checked the max length of the db table and UI
Then check again because you have missed something. That is the only reason you would see that error message. Are you looking at the actual values you're using in your SQL code or the values you think you're using? I notice that the last five values look like you're using the actual controls as the values:
C#:
+ "','" + combomem + "','" + txtproc + "','" + combohdd + "','" + comboOS + "','" + combooffice + "')");
whereas earlier in that line you are using the Text properties of the controls:
C#:
+ "','" + txtsurname.Text + "','" + combodept.Text + "','" + combocompany.Text + "','" + txthostname.Text
If that's the problem then you should have seen that for yourself because you should have already looked at the actual value of cmd.CommandText rather than just the code that constructs it. ALWAYS look at the actual values being used by the code, not just the code that uses them. This is why you MUST use the debugger and watch your code as it executes and not just read it in the code editor.
 
Then check again because you have missed something. That is the only reason you would see that error message. Are you looking at the actual values you're using in your SQL code or the values you think you're using? I notice that the last five values look like you're using the actual controls as the values:
C#:
+ "','" + combomem + "','" + txtproc + "','" + combohdd + "','" + comboOS + "','" + combooffice + "')");
whereas earlier in that line you are using the Text properties of the controls:
C#:
+ "','" + txtsurname.Text + "','" + combodept.Text + "','" + combocompany.Text + "','" + txthostname.Text
If that's the problem then you should have seen that for yourself because you should have already looked at the actual value of cmd.CommandText rather than just the code that constructs it. ALWAYS look at the actual values being used by the code, not just the code that uses them. This is why you MUST use the debugger and watch your code as it executes and not just read it in the code editor.
Thank you so much,
jmcilhinney
Don't know how i missed that, my head is so spinning just looking at the code, i have included .Text behind those without it and ran the debugger and it worked.
 
Back
Top Bottom