Click here to Skip to main content
15,910,661 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i try to use this code to delete records from my database bout i have this error.
my column type for id is (int) where is the problem

C#
List<string> selectedIds = new List<string>();
            foreach (DataGridViewRow item in advancedDataGridView1.Rows)
            {
                if (bool.Parse(item.Cells[0].Value.ToString()))
                {
                    selectedIds.Add("'" + item.Cells[1].Value.ToString() + "'");
                    // collecting all ids
                }
            }
            String sql = "delete from tabl where id in(@idsToDelete)";
            using (SqlConnection cn = new SqlConnection("Data Source=DESKTOP-J7D5POF;Initial Catalog=ilswork;Persist Security Info=True;User ID=***;Password=***"))
            {
                cn.Open();
                using (SqlCommand cmd = new SqlCommand(sql, cn))
                {
                    cmd.Parameters.Add("@idsToDelete", SqlDbType.varchar).Value = string.Join(",", selectedIds);
                    cmd.ExecuteNonQuery();
                }
            }


What I have tried:

CSS
using (SqlCommand cmd = new SqlCommand(sql, cn))
                {
                    cmd.Parameters.Add("@idsToDelete", SqlDbType.Int).Value = string.Join(",", selectedIds);
                    cmd.ExecuteNonQuery();
                }


i get this error (Failed to convert parameter value from a String to a Int32)
Posted
Updated 14-Jan-19 1:30am
v2
Comments
Bryian Tan 13-Jan-19 1:44am    
Look like the code is passing in string instead on int
el_tot93 13-Jan-19 1:58am    
so what should i do

Perhaps a simple way could be to concatenate an individual parameter for each value.

Consider the following example

C#
String sql;
int parameterCounter;
SqlParameter parameter;

sql = "delete from tabl where id in (";
parameterCounter = 0;

using (SqlConnection cn = new SqlConnection("....")) {
   using (SqlCommand cmd = new SqlCommand(sql, cn)) {
      foreach (DataGridViewRow item in advancedDataGridView1.Rows) {
         if (bool.Parse(item.Cells[0].Value.ToString())) {
            parameterCounter++;
            parameter = new SqlParameter();
            parameter.ParameterName = "@par" + parameterCounter.ToString();
            parameter.DbType = System.Data.DbType.Int32;
            parameter.Value = item.Cells[1].Value;
            cmd.Parameters.Add(parameter);
            sql = sql + $"{parameter.ParameterName},";
            // collecting all ids
         }
      }
      sql = sql.TrimEnd(',');
      sql = sql + ")";

      cmd.CommandText = sql;
      cmd.Connection = cn;
      cn.Open();
      cmd.ExecuteNonQuery();
   }
}
 
Share this answer
 
v5
Comments
el_tot93 13-Jan-19 3:24am    
it gave me error System.Data.SqlClient.SqlException: 'Incorrect syntax near ')'.'
Wendelius 13-Jan-19 3:29am    
If you use the debugger, what does the sql string look like?
Wendelius 13-Jan-19 3:31am    
Actually I noticed the problem, The TrimEnd was missing assignment. The example has now been fixed:

sql = sql.TrimEnd(',');
el_tot93 13-Jan-19 3:55am    
now debugger (The parameterized query '(@par1 int)delete from tabl where id in (@par1)' expects the parameter '@par1', which was not supplied.')
Wendelius 13-Jan-19 4:00am    
Sorry, my bad. The value assigment was missing. I don't have a compiler at hand so it's a bit difficult to use just notepad...

In the example the following row has been added

parameter.Value = item.Cells[1].Value;

If you encounter more problems with my code example, let me know.
Why are you trying to pass a collection of "integer" values (when in fact they are integers as strings) formed as a comma separated list of values as a single integer?
cmd.Parameters.Add("@idsToDelete", SqlDbType.Int).Value = string.Join(",", selectedIds);

Of course that isn't going to work! SQL will receive a string like this:
'1,2,3,4'
And try to convert that to a single integer value, fail, and throw an error.

Then when you fix that, there is the other problem: that won't work.
For a solution, see here: Using comma separated value parameter strings in SQL IN clauses[^]
 
Share this answer
 
Comments
el_tot93 13-Jan-19 1:59am    
So what is the right way? I did not understand anything from link ..
Maciej Los 14-Jan-19 7:30am    
5ed!
If i understand you well, you want to pass several parameters into sql command as a single parameter (a list of id's).
C#
List<string> selectedIds = new List<string>();
//...
selectedIds.Add("'" + item.Cells[1].Value.ToString() + "'"); 
//...
String sql = "delete from tabl where id in(@idsToDelete)";
//...
cmd.Parameters.Add("@idsToDelete", SqlDbType.varchar).Value = string.Join(",", selectedIds);

As OriginalGriff mentioned, you're trying to pass string value ('1,2,3,4') into sql command instead of their original values(array of [1,2,3,4]). So, your command is getting single varchar parameter instead of an array of numeric values! This is a main cause of your error. So, you can resolve your issue by:
1) passing every single value into command and execute a command in a loop, but it may be the reason of slow performance. It might looks like dDOS attack[^]!
or
2) passing an array of values into command.
A recommended way is to use Table-Valued Parameters | Microsoft Docs[^]. Follow the link. There you'll find information how to achieve that!
 
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