简体   繁体   中英

I can delete row in DataGridView but it doesn't update my database (C# Form)

I want to delete row from database and datagridview but it is only deleting in datagridview. How can I updated my database? I have found solutions in Internet but they didn't work.

Note: My database is opening in constructor.

private void button1_Click(object sender, EventArgs e)
    {

        SqlCommand cmd = new SqlCommand();
       
        for (int i = 0; i < UserListDataGridView.Rows.Count; i++)
        {
            DataGridViewRow row = UserListDataGridView.Rows[i];
            if (row.Selected == true)
            {
                UserListDataGridView.Rows.RemoveAt(i);
               
                cmd.CommandText = "DELETE FROM UserList WHERE user_id=" + i + "";
                cmd.Connection = DBHelper.DBConnection.ConnectionString;
                cmd.ExecuteNonQuery();
          
            }               
        }
    }

I found a solution. This code is working:

private void DeleteButton_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow item in this.UserListDataGridView.SelectedRows)
        {

            SqlCommand cmd = DBHelper.DBConnection.ConnectionString.CreateCommand();
            int id = Convert.ToInt32(UserListDataGridView.SelectedRows[0].Cells[0].Value);
            cmd.CommandText = "Delete from UserList where user_id='" + id + "'";

            UserListDataGridView.Rows.RemoveAt(this.UserListDataGridView.SelectedRows[0].Index);

            cmd.ExecuteNonQuery();
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM