我需要从datagridview删除选定的行

时间:2019-07-09 08:39:57

标签: c# winforms

我想从数据库中删除DataGridView中的选定行,但得到另一个索引。有什么建议我做错了什么吗? enter image description here

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();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

我认为您的方法不正确,因为您要遍历选定的单元格。如果连续选择多个单元格,会发生什么情况。您会两次删除该行吗?

我建议以下内容:

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]);
        }
    }
}

答案 1 :(得分:0)

我很确定问题出在您的

dataGridView1.Rows.RemoveAt(oneCell.RowIndex);

在这里,您似乎正在从DataGridView中删除该行。因此,当您尝试使用oneCell.RowIndex从单元格获取索引时,该行不再是DataGridView => RowIndex -1

的一部分

尝试访问索引后,请从row中删除DataGridView

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);
        }
    }
}

编辑:
正如评论中的其他人已经提到的那样,首先使用RowIndex作为数据库的id并不是最好的主意。