0

在下面的代码中,UPDATE 有效,但 DELETE 无效。当我删除行时,它会删除它并且 GridView1 没有显示它,但数据库仍然有它。customersPrimaryKey

using (SqlConnection connection = new SqlConnection(conString))
        {
            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = new SqlCommand("select * from customers", connection);
            SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
            connection.Open();
            DataTable customers = new DataTable();
            adapter.Fill(customers);
            // code to modify data in DataTable here
        customers.Rows.RemoveAt(rowIndex);
            GridView1.EditIndex = -1;
            GridView1.DataSource = customers;
            GridView1.DataBind();
            adapter.Update(customers);
4

1 回答 1

1

您不想从 DataTable 中删除该行,而是将其删除

必须将DataRow 的DataRowState修改为deleted,然后 DataAdapter 知道它必须在数据源中将其删除。

以下将删除它:

customers.Rows(rowIndex).delete();//now DataRow's DataRowState is Deleted
adapter.Update(customers);        // now it's actually deleted

更多信息:MSDN How to: Delete Rows in a DataTable

顺便说一句,如果您改变主意,以下将防止 DataRow 被删除:

customers.Rows(rowIndex).RejectChanges();

RowState 将变回Unchanged. 这适用于DataRow整个 DataTable

于 2011-10-04T21:32:06.517 回答