I'm trying to remove an entry from both the datagridview and the database. I got it so it removes the row from the data grid view but it fails to delete it also from the database. Here is my code I have in place:
private void listBtn_Click(object sender, EventArgs e)
{
MySqlDataAdapter mysqldatadapter = new MySqlDataAdapter("select id, username from members ORDER BY id", new MySqlConnection(conn.connectionString));
mysqldatadapter.Fill(ds);
dataGridView.DataSource = ds.Tables[0];
listBtn.Enabled = false;
}
private void btnDelete_Click(object sender, EventArgs e)
{
using (MySqlConnection dbConn = new MySqlConnection(conn.connectionString))
{
dbConn.Open();
for (int i = 0; i < dataGridView.Rows.Count; i++)
{
DataGridViewRow row = dataGridView.Rows[i];
if (row.Selected == true)
{
dataGridView.Rows.RemoveAt(i);
MySqlCommand cmd = dbConn.CreateCommand();
cmd.CommandText = "DELETE FROM members WHERE id = " + i;
try
{
cmd.ExecuteNonQuery();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
}
dbConn.Close();
}
}
I'm at a loss concerning this, any help would be appreciated.
Thanks!
Update - Is there a way to grab the value of individual cells to pass to the mysql command? For instance, grabbing the id?
Your values for i
probably don't match the id
fields in the member
table.
You probably need to change this line:
cmd.CommandText = "DELETE FROM members WHERE id = " + i;
to
cmd.CommandText = "DELETE FROM members WHERE id = " + row.cells[id.Index].ToString();
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.