Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi all,
I am new in the team and new in C#, so below i have this code, i am trying to pass values from gridview to the database... so, I am getting this message: "Conversion failed when converting the varchar Valor value to data type int"
I appreciate your help, thanks
C#
System.Data.SqlClient.SqlConnection sqlConnection1 = new System.Data.SqlClient.SqlConnection
(@"Data Source=HP\SQLEXPRESS;Initial Catalog=Storebook;User ID=****;Password=********");

            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
            cmd.CommandType = System.Data.CommandType.Text;
            cmd.CommandText = "INSERT INTO Itens (Price) " +
                    "VALUES ('@Num')";
            cmd.Connection = sqlConnection1;

            sqlConnection1.Open();

            for (int i = 0; i < itensDataGridView.Rows.Count; i++)
            {
                cmd.Parameters.Clear();
                int Valor = Convert.ToInt32(itensDataGridView.Rows[i].Cells[1].Value);
                cmd.Parameters.AddWithValue("@Price", Valor);

                cmd.ExecuteNonQuery();
                sqlConnection1.Close();
            }
Posted
Updated 11-Jul-14 4:15am
v3

Correct your query -
SQL
cmd.CommandText = "INSERT INTO Itens (Price) " +
"VALUES (@Num)

Remove the single quotes.

As a note, Itens may be the wrong table(Items maybe?).
 
Share this answer
 
v2
Comments
CHill60 11-Jul-14 10:19am    
Overlap! You type quicker than me :)
The problem is with your sql
SQL
cmd.CommandText = "INSERT INTO Itens (Price) " + "VALUES ('@Num')";


Change it to
SQL
cmd.CommandText = "INSERT INTO Itens (Price) " +
        "VALUES (@Num)";

I removed the single quotes surround the parameter which were forcing the value to be a varchar.

Parameterised queries take care of the single quotes when you add varchar values so you don't need them in your base sql string then either
 
Share this answer
 
I would not have noticed, thanks for the help.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900