Wednesday, August 29, 2007

ADODB Promptdatasource in .NET

In Delphi Win32 it is very easy to use the standard Windows OleDB datalink connection dialog to build Connectionstrings at runtime.


It is as simple as this, use ADODB and you have the PromptDataSource function:

ConnString := PromptDataSource(Handle, ConnString);

In .NET however it is a little more complex. To make a function that can do this, you must first add references to both the Microsoft ActiveX Data Objects 2.8 Library (=ADODB namespace) and the Microsoft OLE DB Service Component 1.0 Type Library (=MSDASC namespace). In C# the code looks something like this:

private string PromptDataSource()
{
MSDASC.DataLinks dataLinks = new MSDASC.DataLinksClass();
ADODB.Connection connection = new ADODB.ConnectionClass();
object oConnection = (object)connection;
if (dataLinks.PromptEdit(ref oConnection))
return connection.ConnectionString;
else
return "";
}


In Delphi .NET the code looks like this:

uses ADODB, MSDASC; (Add to your uses clause).

function TForm1.PromptDatasource : string;
var
Datalinks : DataLinksClass;
ADOConnection : Connection;
oConnection : TObject;
begin
Result := '';
Datalinks := DataLinksClass.Create;
ADOConnection := ADODB.ConnectionClass.Create;
oConnection := TObject(ADOConnection);
if Datalinks.PromptEdit(oConnection) then begin
Result := ADOConnection.ConnectionString;
end;
end;



In Delphi .NET it is wise to remove the namespace prefixing.
Default there is a prefix Borland.VCL. If you don't remove that the compiler will use the Borland.VCL.ADODB namespace instead of the ADODB namespace from the COM import.
You can do this in the options dialog under Tools.
(Or alter your project specific namespace prefixes in the project options)

No comments: