将DataGridView的更改保存到数据库

时间:2015-10-31 11:48:21

标签: c# datagridview

我的表单中包含DataGridView和删除Button 我有这个代码删除一行,怎么能把这个删除保存到数据库?我用dataGridView1填充了DataSet

if (dataGridView1.Rows.Count > 0)
{
    if (dataGridView1.Rows[dataGridView1.CurrentRow.Index].IsNewRow != true)
    {
        dataGridView1.Rows.Remove(dataGridView1.CurrentRow);     
    }
}

1 个答案:

答案 0 :(得分:1)

假设您的Table中有一个名为id的列,并且您希望根据id从数据库中删除。试试这个:

private void btnDelete_Click(object sender, EventArgs e)
{
    foreach (DataGridViewRow item in dataGridView1.SelectedRows)
    {
       var id = item.Cells[0].Value.ToString();//You can change id and Cells[0] as your need
       //Write Delete code like this (Delete from Table where id = @id)
       dataGridView1.Rows.RemoveAt(item.Index);//Remove from dataGridView1
    }
}