C#删除SQL绑定数据网格视图中的单行

时间:2017-07-23 05:53:03

标签: c# sql datagridview

我尝试了许多解决方案,只说明​​一行被删除但在我的VS2017 C#中从所选行到DataGridView的末尾都删除了所有行。如果我有5行并删除第4行,则删除第4行和第5行。我可以添加没有问题的行,我可以删除表并创建表,但删除单行数据似乎不可行。

请帮助,我已经在这里待了几天......

private void DDataTable_UserDeletedRow( object sender, DataGridViewRowEventArgs e )
{
  try
  {
    // Want the last operation to be completed
    dbDataSetBindingSource.EndEdit();
    //dbTableAdapter.Update( dbDataSet );

    if ( selectedCellRow > 0 )
    {
      DataRowView drv = ( DataRowView )dbDataSetBindingSource.Current;
      DataRow drToDelete = drv.Row;
      dbDataSet.MyTable.Rows.Remove( drToDelete );
    // This removed all remaining rows
    //  DDataTable.Rows.Remove( this.DDataTable.SelectedRows[ 0 ] );
    // This removed all remaining rows 
    //  dbDataSetBindingSource.RemoveCurrent();
    // This gave an error "Can't remove items not in the list?
    //  dbDataSetBindingSource.Remove( selectedRowStr );

      dbDataSetBindingSource.EndEdit();
      dTableAdapter.Update(dbDataSet);
    }
    else
      MessageBox.Show( "Error in delete row, bad index." );
  }
  catch (Exception ex)
  {
  //  CancelEventArgs myE = new CancelEventArgs();
  //  DDataTable_Validating( sender, myE );
    string myStr = "Error in deleting row\n" + ex.Message;
    MessageBox.Show( myStr, "User Delete a Row" );
  }
}

1 个答案:

答案 0 :(得分:0)

您可以致电drToDelete.Delete(),然后致电dbDataSet.MyTable.AcceptChanges();

更新数据集

或者您可以致电:

dbDataSet.MyTable.Rows.RemoveAt(dbDataSetBindingSource.Position);

希望这有帮助。