Search code examples
delphitclientdatasetdbgrid

DBGrid is not refreshing after deleting record from database


I wondering why my DBGridEh (descendant DBGrid) is not refreshing after I deleted a record in the database using the following MRE. You will find my 4 attempts commented below but no luck. The deletion basically works but the DBGrid does not update or disconnects from datasource.

procedure TForm9.btnDeleteClick(Sender: TObject);
begin
  //cds1.DisableControls; //attempt 1 failed. It deletes the record but not changes on the DBGrid
  uq1.SQL.Clear;
  uq1.SQL.Text := 'DELETE FROM mymachine WHERE ListID = :Pid';
  uq1.Params.ParamByName('Pid').Value := cds1.FieldByName('ListID').AsInteger;
  uq1.ExecSQL;
  //cds1.EnableControls;  //attempt 1 failed. It deletes the record but not changes on the DBGrid
  //cds1.Active := False; //attempt 2 failed. "SQL Statement doesn't return rows." but it deletes and cleared the data on the DBGrid (seemed disconnected from datasource) 
  //cds1.Active := True;  //attempt 2 failed. "SQL Statement doesn't return rows." but it deletes and cleared the data on the DBGrid (seemed disconnected from datasource) 
  //cds1.Close;           //attempt 3 failed. "SQL Statement doesn't return rows." but it deletes and cleared the data on the DBGrid (seemed disconnected from datasource) 
  //cds1.Open;            //attempt 3 failed. "SQL Statement doesn't return rows." but it deletes and cleared the data on the DBGrid (seemed disconnected from datasource)
  //cds1.Refresh;         //attempt 4 failed. "SQL Statement doesn't return rows." but it deletes and DBGrid data remains
end;

UPDATE VCL.FILE

  object dgh1: TDBGridEh

  object ucn1: TUniConnection
    ProviderName = 'mySQL'
    Port = 3306
    Database = 'manufacturingmngtsystem'
    Username = 'root'
    Server = 'localhost'
    Connected = True
    LoginPrompt = False
    Left = 16
    Top = 200
  end
  object mup1: TMySQLUniProvider

  end
  object uq1: TUniQuery
    Connection = ucn1
    SQL.Strings = (
      'Select * From mymachine')
  end
  object dsp1: TDataSetProvider
    DataSet = uq1
  end
  object cds1: TClientDataSet
    Active = True
    Aggregates = <>
    Params = <>
    ProviderName = 'dsp1'
    object intgrfldcds1ListID: TIntegerField
      FieldName = 'ListID'
    end
    object strngfldcds1Name: TStringField
      FieldName = 'Name'
      Required = True
      Size = 36
    end
    object strngfldcds1Description: TStringField
      FieldName = 'Description'
      Size = 209
    end
    object strngfldcds1Status: TStringField
      FieldName = 'Status'
      Required = True
      FixedChar = True
      Size = 8
    end
  end
  object ds1: TDataSource
    DataSet = cds1
  end
end

Solution

  • As the grid is connected to the dataset cds1, a simple cds1.Delete will do the trick. This might have to be followed by a call to cds1.ApplyUpdates to forward the changes to the underlying database.