c# – 如何从datagridview和数据库中删除选定的行

这个想法是删除时选择的行将从datagridview,数据库中删除,然后datagridview将被刷新.我假设它必须使用SQL完成,但是如何将类型为text的sqlcommand与该特定行的删除代码相关联?
数据库由一个表组成,数据网格绑定到该表.

删除按钮:

private void btnBookRecord_Click(object sender, EventArgs e)
{
    if (this.BooksGrid.SelectedRows.Count > 0)
    {
        foreach (DataGridViewRow dgvrCurrent in BooksGrid.SelectedRows)
        {
            if (dgvrCurrent == BooksGrid.CurrentRow)
            {
                BooksGrid.CurrentCell = null;
            }

            // Delete row code here
        }
    }
}
由于某种原因,即使我从添加按钮复制刷新代码,datagridview也不会更新.但它确实从数据库中删除了记录.

private void deleteRecord()
{
    if (BooksGrid.SelectedRows.Count > 0)
    {
        int selectedIndex = BooksGrid.SelectedRows[0].Index;

        int rowID = int.Parse(BooksGrid[0, selectedIndex].Value.ToString());
        string sql = "DELETE FROM Table1 WHERE RowID = @RowID";

        SqlCommand deleteRecord = new SqlCommand();
        deleteRecord.Connection = Booksconnection;
        deleteRecord.CommandType = CommandType.Text;
        deleteRecord.CommandText = sql;

        SqlParameter RowParameter = new SqlParameter();
        RowParameter.ParameterName = "@RowID";
        RowParameter.SqlDbType = SqlDbType.Int;
        RowParameter.IsNullable = false;
        RowParameter.Value = rowID;

        deleteRecord.Parameters.Add(RowParameter);

        deleteRecord.Connection.Open();

        deleteRecord.ExecuteNonQuery();

        deleteRecord.Connection.Close();

        booksDataset1.GetChanges();

        sqlDataAdapter1.Fill(booksDataset1.Videos);
    }
}
相关文章
相关标签/搜索