Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i use this code to delete selected datagrid from data base but it is not delete

C#
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
   DataGridViewRow dr = dataGridView1.Rows[i];
   if (dr.Selected == true)
   {
      dataGridView1.Rows.RemoveAt(i);
      try
      {
         SqlCommand cmd = new SqlCommand("Delete from calender where ID= ' " + i + "'", con);     
         cmd.ExecuteNonQuery();
         con.Close();
      }
      catch (Exception ex)
      {
         MessageBox.Show(ex.ToString());
      }
   }
}


[edit]code block added and indexation fixed[/edit]
Posted
Updated 16-Nov-12 23:09pm
v2
Comments
faisal23 17-Nov-12 4:15am    
windows / web
n.podbielski 17-Nov-12 6:11am    
No problem? No error?
meme_307 17-Nov-12 6:33am    
i want to delete data from data grid
the not deleted from database
i worked in windows
i make button to delete the selected row from grid ,, it delete just from grid not data base
pryashrma 17-Nov-12 7:08am    
does value of database field "ID" and variable "i" are same?
meme_307 17-Nov-12 7:26am    
no it is not the same so it is not delete ,,,
,,,
now i need delete code to delete the selected row from database

1 solution

Hi
Can you try after removing space between single quotes and double quotes from query.
I.E

C#
SqlCommand cmd = new SqlCommand("Delete from calender where ID= '" + i + "'", con);
 
Share this answer
 
Comments
meme_307 17-Nov-12 6:53am    
i tried it's not delete from database
Dominic Abraham 17-Nov-12 7:06am    
Can you try directly removing the value from database after giving a value for i. I.E . Execute the query
Delete from calender where ID = '1' in database. Just to make sure that, there is no issues with your query/data. And if you are able to delete the data, just try the same query from code [after inserting the deleted data]

ie.

SqlCommand cmd = new SqlCommand("Delete from calender where ID= '1'", con);
cmd.ExecuteNonQuery();
con.Close();

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