Click here to Skip to main content
15,881,844 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, i am trying to insert data from datagridview to sql server.
The problem is that in my datagridview , i have decimal values with max 18 number after , and it's only inserting in the database the values with 0 after , .

What I have tried:

I've tried to convert the value in my datagridview to deciaml but not working.
Convert.ToDecimal(dataGridView1.Rows[i].Cells[1].Value)

Also i tried DefaultCellStyle.Format and also not working.
dataGridView1.Columns["solde"].DefaultCellStyle.Format = "N2";
Posted
Updated 26-Jul-22 21:44pm
Comments
Richard Deeming 26-Jul-22 8:36am    
There's probably something wrong with the code you're using to update the database. Unfortunately, since you haven't shown any of the code, we can't tell you what.

At a guess, you may be using string concatenation to build your query, rather than using a properly parameterized query. This will leave you vulnerable to SQL Injection[^], as well as introducing problems with regional formats.
houssem eddine ayari 27-Jul-22 3:31am    
This is my code to insert in the database from datagridview :
SqlCommand cc = new SqlCommand("INSERT INTO [dbo].[C9_V] ([C9],[V],[OID],[USERMODIF]) VALUES ('" + dataGridView1.Rows[i].Cells[0].Value + "', '" + dataGridView1.Rows[i].Cells[1].Value + "', '" + textBox1f2.Text + "', '" + user + "')", conn);
cc.ExecuteNonQuery();
Richard Deeming 27-Jul-22 4:39am    
using (SqlCommand cc = new SqlCommand("INSERT INTO [dbo].[C9_V] ([C9],[V],[OID],[USERMODIF]) VALUES (@C9, @V, @OID, @USERMODIF)", conn))
{
    cc.Parameters.AddWithValue("@C9", dataGridView1.Rows[i].Cells[0].Value);
    cc.Parameters.AddWithValue("@V", dataGridView1.Rows[i].Cells[1].Value);
    cc.Parameters.AddWithValue("@OID", textBox1f2.Text);
    cc.Parameters.AddWithValue("@USERMODIF", user);
    cc.ExecuteNonQuery();
}
houssem eddine ayari 27-Jul-22 6:05am    
i've tried before this and my problem still persist
CHill60 27-Jul-22 12:46pm    
Can you share a couple of examples of the data you inserting into the database and what you are getting back. Can you also share with us the column definitions of the table?

1 solution

@Richard-Deeming was correct in his guess then. You should never use string concatenation to build SQL queries.
Use Parameterised Queries instead - see Query Parameterization - OWASP Cheat Sheet Series[^]. Apart from helping to protect you from SQL injection it also solves a multitude of problems around data types.
 
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