title: C# Delete selected row from datagrid and database
body: <p>Apologies in advance if this is a mundane question or has a lack of information, I am new to both software development and the stack overflow community.</p>
  
  <p><strong>For clarification purposes:</strong> </p>
  
  <ul>
  <li>I am using the AdventureWorks Sample Database in SQL Server 2012 and I have created a table named Users. </li>
  <li>I am using C# </li>
  </ul>
  
  <p><strong>Overview of what im trying to achieve and the problem:</strong></p>
  
  <p>The user should be able to select a row in the datagridview and select the delete button to delete the chosen user from the database. When running my code the row is deleted from the datagridview but not the database and as upon refreshing the datagridview the record returns and I'm not quite sure where I have gone wrong .. </p>
  
  <pre><code>    private void btnDelete_Click(object sender, EventArgs e)
      {
          delete_record();
  
          SqlConnection conn = new SqlConnection();
          SqlCommand delcmd = new SqlCommand();
          conn.ConnectionString = "server=localhost;Trusted_connection=yes;database=AdventureWorks2012";
          conn.Open();
  
          SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Users", conn);
          DataTable dt = new DataTable();
          da.Fill(dt);
          dbgrid1.DataSource = dt;
          conn.Close();
      }
  
  
      private void delete_record()
      {
          SqlConnection conn = new SqlConnection();
          SqlCommand delcmd = new SqlCommand();
          conn.ConnectionString = "server=localhost;Trusted_connection=yes;database=AdventureWorks2012";
          if (dbgrid1.Rows.Count &gt; 1 &amp;&amp; dbgrid1.SelectedRows[0].Index != dbgrid1.Rows.Count - 1)
          {
              delcmd.CommandText = "DELETE FROM Users WHERE ID=" + dbgrid1.SelectedRows[0].Cells[0].Value.ToString() + "";
              conn.Open();
              delcmd.Connection = conn;
              delcmd.ExecuteNonQuery();
              conn.Close();
              dbgrid1.Rows.RemoveAt(dbgrid1.SelectedRows[0].Index);
              MessageBox.Show("deleted");
          }
      }
  </code></pre>