title: How to delete a selected row from datagridview?
body: <pre><code>if (dgvProductCatalog.Rows.Count &gt; 1 &amp;&amp; dgvProductCatalog.SelectedRows[0].Index != dgvProductCatalog.Rows.Count - 1)
  
  {
   cmd = new SqlCommand("DELETE FROM Products WHERE ProductId= " + dgvProductCatalog.SelectedRows[0].Cells[0].Value.ToString() + " " , connection);
                  try
                  {
                      connection.Open();
                      cmd.ExecuteNonQuery();
                  }
                  catch (SqlException ex)
                  {
                      MessageBox.Show(ex.Message);
                  }
                  finally
                  {
                      connection.Close();
                      dgvProductCatalog.Rows.RemoveAt(dgvProductCatalog.SelectedRows[0].Index);
                      MessageBox.Show("Record Deleted Successfully!");
                      DisplayData();
                      ClearData();
                  }
  }
  </code></pre>
  
  <p>I am using the above piece of code on a button click to delete a selected row but i am getting 
  "<strong>System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.</strong>" What am I doing wrong here?</p>
  
  <p>Thanks!</p>