I am programmatically creating a database connection object inside a simple procedure (not a method in a class).
mydb:= TUniConnection.Create(nil);
mydb.Database:= knowledge_db_name;
mydb.LoginPrompt:= False;
mydb.Username:= aaa;
mydb.Password:= bbb;
now I need to handle errors and disconnections with other procedures. When I try to do:
mydb.OnError:= OnConnectionError;
mydb.OnConnectionLost:= OnConnectionLost;
The compiler tells me
[DCC Error] test.pas(373): E2009 Incompatible types: 'method pointer and regular procedure'
How can I work around this? Here are the definitions of the event procedures:
procedure OnConnectionError(Sender: TObject; E: EDAError; var Fail: Boolean);
procedure OnConnectionLost(Sender: TObject; Component: TComponent; ConnLostCause: TConnLostCause; var RetryMode: TRetryMode);
If you don't have a suitable class to put the event handlers in you can define a dummy class and make the event handlers class procedure
s. Then you don't have to create an instance of the class but can assign mydb.OnError:= TMyDummyEventHandlerClass.OnConnectionError;
.
Here is an example - I use different events because I don't have TUniConnection
but want to be sure everything compiles. :-)
type
// Dummy class to hold event handlers:
TXMLEventHandlers = class
// Event handlers:
class procedure OnBeforeOpen(Sender: TObject);
class procedure OnAfterOpen(Sender: TObject);
end;
class procedure TXMLEventHandlers.OnBeforeOpen(Sender: TObject);
begin
MessageBox(0, PChar(ClassName + '.OnBeforeOpen'), nil, 0)
end;
class procedure TXMLEventHandlers.OnAfterOpen(Sender: TObject);
begin
MessageBox(0, PChar(ClassName + '.OnAfterOpen'), nil, 0)
end;
procedure Test;
var
xml: TXMLDocument;
begin
xml := TXMLDocument.Create(nil);
try
// Note: No instance of `TXMLEventHandlers` must be created:
xml.AfterOpen := TXMLEventHandlers.OnAfterOpen;
xml.BeforeOpen := TXMLEventHandlers.OnBeforeOpen;
xml.Active := True; // Calls the two event handlers
finally
xml.Free;
end;
end;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With