I want to delete the selected row in the DataGridView
from a database but I get a different index. Any suggestions where I'm doing something wrong?
private void Button3_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
{
if (oneCell.Selected)
{
dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
string deleteQuery = $"DELETE FROM {comboBox1.SelectedItem} WHERE id= " + oneCell.RowIndex;
form1.conn = new SqlConnection($"Server = {form1.ServerBox.Text }; Database = { form1.DBBox.Text}; Trusted_Connection = True");
form1.cmd = new SqlCommand(deleteQuery, form1.conn);
form1.conn.Open();
form1.cmd.ExecuteNonQuery();
form1.conn.Close();
}
}
}
I'm pretty sure the problem lies with your
dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
Here you seem to be deleting the row from the DataGridView
. Therefore when you're trying to get the index from the cell with oneCell.RowIndex
it is no longer in any row that's part of the DataGridView
=> RowIndex -1
Try deleting the row
from the DataGridView
after trying to access the index:
private void Button3_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
{
if (oneCell.Selected)
{
string deleteQuery = $"DELETE FROM {comboBox1.SelectedItem} WHERE id= " + oneCell.RowIndex;
form1.conn = new SqlConnection($"Server = {form1.ServerBox.Text }; Database = { form1.DBBox.Text}; Trusted_Connection = True");
form1.cmd = new SqlCommand(deleteQuery, form1.conn);
form1.conn.Open();
form1.cmd.ExecuteNonQuery();
form1.conn.Close();
dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
}
}
}
Edit:
As others in the comments have already mentioned, it's probably not the best idea to use a RowIndex
as an id
for a database in the first place.
I think your approach is not correct as you are iterating through selected cells. What happens if you select more than one cells in a row. Will you delete this row twice?
I propose following:
private void Button3_Click(object sender, EventArgs e)
{
var selectedRows = dataGridView1.SelectedRows.Cast<DataGridViewRow>().ToArray();
for (int i = 0; i < selectedRows.Length; i++)
{
if(selectedRows[i].Cells[idColumn.Index].Value is int id)
{
string deleteQuery = $"DELETE FROM {comboBox1.SelectedItem} WHERE id= " + id;
form1.conn = new SqlConnection($"Server = {form1.ServerBox.Text }; Database = { form1.DBBox.Text}; Trusted_Connection = True");
form1.cmd = new SqlCommand(deleteQuery, form1.conn);
form1.conn.Open();
form1.cmd.ExecuteNonQuery();
form1.conn.Close();
dataGridView1.Rows.Remove(selectedRows[i]);
}
}
}
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.