Deleting Selected Data From Database in Windows Forms

Here I will explain how to delete selected data from a database, before this I explain how to update or edit data.

Step 1: Registration form with delete button

delete button

Drag and drop a button from the toolbox and provide it the name Delete.

Step 2: The following is the code:
 
code

Double-click on the Delete button and write the following code.
  1. private void Delete_txt_Click(object sender, EventArgs e)  
  2. {  
  3. if (!(id_txt.Text == string.Empty))  
  4. {  
  5. string str = "server = MUNESH\\SQL2008R2;Database=datastore;UID=sa;Password=reladmin@123;";  
  6. SqlConnection con = new SqlConnection(str);  
  7. string query = "Delete from data1 where ID= '" + this.id_txt.Text + "'";  
  8. SqlCommand cmd = new SqlCommand(query, con);  
  9. SqlDataReader myreader;  
  10. try  
  11. {  
  12. con.Open();  
  13. myreader = cmd.ExecuteReader();  
  14. MessageBox.Show("successfully data Deleted","user information");  
  15. while (myreader.Read())  
  16. {  
  17. }  
  18. con.Close();  
  19. }  
  20. catch (Exception ec)  
  21. {  
  22. MessageBox.Show(ec.Message);  
  23. }  
  24. }  
  25. else  
  26. {  
  27. MessageBox.Show("enter ID which you want to delete","User information");  
  28. }  

 

Step 3: Output

Run your project and enter an ID and click on the delete button.

Output
You can also go to my blog-munesh.

Up Next
    Ebook Download
    View all
    Learn
    View all