且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从DataGridView和数据库中删除选定的行

更新时间:2023-02-06 23:39:50

由于某种原因在DataGridView将不会更新,即使我复制从添加按钮,它的工作原理刷新代码。但它确实删除数据库中的记录。

 私人无效deleteRecord()
{
如果(BooksGrid .SelectedRows.Count大于0)
{
INT的selectedIndex = BooksGrid.SelectedRows [0]的.index;

INT ROWID = int.Parse(BooksGrid [0的selectedIndex] .Value.ToString());
字符串SQL =DELETE FROM表1 WHERE的RowID = @RowID;

的SqlCommand deleteRecord =新的SqlCommand();
deleteRecord.Connection = Booksconnection;
deleteRecord.CommandType = CommandType.Text;
deleteRecord.CommandText = SQL;

的SqlParameter RowParameter =新的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);
}
}


The idea is that the row that is selected when deleted gets removed from datagridview, database and then datagridview gets refreshed. I assume it has to be done with SQL but how would you link that sqlcommand of type text with a delete code with that particular row? The database consists of one single table and the datagrid is bound to it.

Delete button:

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

For some reason the datagridview won't update, even though I copied the refresh code from add button which works. But it does delete the record from database.

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