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

时间:2011-04-04 13:32:28

标签: c# winforms datagridview row delete-row

我们的想法是,删除时选择的行将从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
        }
    }
}

3 个答案:

答案 0 :(得分:6)

由于某种原因,即使我从添加按钮复制了刷新代码,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);
    }
}

答案 1 :(得分:3)

如果只允许在DataGridView中进行一次选择,则可以执行此操作。

假设DataGridView中的第一列是数据库中行的标识种子。

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

     // gets the RowID from the first column in the grid
     int rowID = int.Parse(BooksGrid[0, selectedIndex].Value.ToString());

     string sql = "DELETE FROM Table1 WHERE RowID = @RowID";

     // your code for deleting it from the database

     // then your code for refreshing the DataGridView
}

答案 2 :(得分:-2)

DataGridView datagridview1;

datagridview1.Rows.remove(datagridview1.SelectedRows[0]);