如何删除选定的DataGridView行并更新连接的数据库表?

55

我在一个使用C#编写的Windows窗体应用程序中有一个DataGridView控件。

我需要的是:当用户选择了一个DataGridViewRow并点击“删除”按钮时,该行应被删除,接着使用表适配器更新数据库。

这是我目前的代码:

private void btnDelete_Click(object sender, EventArgs e)
{
    if (this.dataGridView1.SelectedRows.Count > 0)
    {
        dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
    }                
}

此外,这仅删除一行。我希望用户可以选择多行。

21个回答

91

以下代码可以删除 dataGridView1 中被选中的项:

 private void btnDelete_Click(object sender, EventArgs e)
 {
     foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
     {
         dataGridView1.Rows.RemoveAt(item.Index);
     }
 }

8
通常来说,修改与迭代对象相关的对象并不总是安全的,而且索引可能没有更新。 - moltenform
14
最佳实践建议使用for循环而不是foreach循环,并从末尾开始迭代。这有助于保留索引并避免在迭代期间编辑时出现问题。 - Grungondola
1
@Grungondola,你应该为此提供一个单独的答案。 - User

22
private void buttonRemove_Click(object sender, EventArgs e)
{
    foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
    {
        if (oneCell.Selected)
            dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
    }
}

删除在所选单元格中的行。因此,请选择任何单元格,它们对应的行将被删除。


10

我写了下面的代码,请看一下:

foreach (DataGridViewRow row in dataGridView1.SelectedRows)
    if (!row.IsNewRow) dataGridView1.Rows.Remove(row);

仍然可以使用所选行的Index,看看下面的代码是否可行:

int selectedCount = dataGridView1.SelectedRows.Count;           
while (selectedCount > 0)
{
    if (!dataGridView1.SelectedRows[0].IsNewRow)
        dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
    selectedCount--;
}
我希望这可以帮到你,祝好。

谢谢... 我现在遇到的主要问题是使用 TableAdapters 将数据保存到数据库中。 - Woody
你需要提供更多关于你遇到的问题的细节;我敢打赌,如果你在新问题中附上引起麻烦的代码片段,你会得到最好的回答。 - serge_gubenko

4
private void btnDelete_Click(object sender, EventArgs e)
{
    if (e.ColumIndex == 10)// 10th column the button
    {
        dataGridView1.Rows.Remove(dataGridView1.Rows[e.RowIndex]);
    }                
}

通过 "e" 参数,此解决方案可以删除一行(非选择的、点击的行!)。


为什么不使用foreach呢?参考@Navid Farhadi的答案。 - knoxgon

3
也许您可以使用临时列表进行删除,以忽略行索引更改。

<pre>
private void btnDelete_Click(object sender, EventArgs e)
{
    List<int> wantdel = new List<int>();
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        if ((bool)row.Cells["Select"].Value == true)
        wantdel.Add(row.Index);
    }

    wantdel.OrderByDescending(y => y).ToList().ForEach(x =>
    {
        dataGridView1.Rows.RemoveAt(x);
    });           
}
</pre>


1

通常我会这样从用户选择的 DataGridView 行中删除,如果您将其与来自 Dataset 的 DataTable 关联(例如:DataGridView1.DataSource = Dataset1.Tables["x"]),那么一旦您在 Dataset 中进行任何更新(删除、插入、更新),它将自动在您的 DataGridView 中发生。

if (MessageBox.Show("Are you sure you want to delete this record(s)", "confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.Yes)
        {
            try
            {
                for (int i = dgv_Championnat.RowCount -1; i > -1; i--)
                {
                    if (Convert.ToBoolean(dgv_Championnat.Rows[i].Cells[0].Value) == true)
                    {
                        Program.set.Tables["Champ"].Rows[i].Delete();
                    }
                }
                Program.command = new SqlCommandBuilder(Program.AdapterChampionnat);
                if (Program.AdapterChampionnat.Update(Program.TableChampionnat) > 0)
                {
                    MessageBox.Show("Well Deleted");
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

1

在 C# 中删除数据表格中的多行

我的代码部分:

private void btnDelete_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in datagrid1.SelectedRows)
        {
            //get key
            int rowId = Convert.ToInt32(row.Cells[0].Value);

            //avoid updating the last empty row in datagrid
            if (rowId > 0)
            {
                //delete 
                aController.Delete(rowId);

                //refresh datagrid
                datagrid1.Rows.RemoveAt(row.Index); 
            }  
        }
    }




 public void Delete(int rowId)
        {
            var toBeDeleted = db.table1.First(c => c.Id == rowId);
            db.table1.DeleteObject(toBeDeleted);
            db.SaveChanges();

        }

1
private: System::Void button9_Click(System::Object^  sender, System::EventArgs^  e)
{
    String^ constring = L"datasource=localhost;port=3306;username=root;password=password";
    MySqlConnection^ conDataBase = gcnew MySqlConnection(constring);
    conDataBase->Open();
    try 
    {
        if (MessageBox::Show("Sure you wanna delete?", "Warning", MessageBoxButtons::YesNo) == System::Windows::Forms::DialogResult::Yes)
        {
            for each(DataGridViewCell^ oneCell in dataGridView1->SelectedCells)
            {
                if (oneCell->Selected) {
                    dataGridView1->Rows->RemoveAt(oneCell->RowIndex);
                    MySqlCommand^ cmdDataBase1 = gcnew MySqlCommand("Delete from Dinslaken_DB.Configuration where Memory='ORG 6400H'");
                    cmdDataBase1->ExecuteNonQuery();
                    //sda->Update(dbdataset);
                }   
            }           
        }
    }
    catch (Exception^ex)
    {
        MessageBox::Show(ex->ToString());
    }
}

1

当用户在DataGridView中选择时,此命令将删除所选行:

gvTest.Rows.RemoveAt(dvTest.CurrentRow.Index];


0
这对我来说有效:
private void btnRemove_Click(object sender, EventArgs e) {
    int count = dgvSchedule.SelectedRows.Count;

    while (count != 0) {
        dgvSchedule.Rows.RemoveAt(dgvSchedule.SelectedRows[0].Index);
        count--;
    }
 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接