2004. június 11., péntek

Better way to display [error] messages


Problem/Question/Abstract:

Better way to display [error] messages

Answer:

If you display more than a few [error] messages in your application, using a simple method such as the following may not be the best approach:

Application.MessageBox('File not found', 'Error', mb_OK);

Above method of displaying errors will make it harder to modify actual messages since they are distributed all over your application source code. It may be better to have a "centralized" function that can display error messages, or better yet, a centralized function that can display replaceable error messages. Consider the following example:

type
  cnMessageIDs =
    (
    nMsgID_NoError,
    nMsgID_FileNotFound,
    nMsgID_OutOfMemory,
    nMsgID_ExitProgram
    // list your other error
    // IDs here...
    );

const
  csMessages_ShortVersion: array[Low(cnMessageIDs)..High(cnMessageIDs)] of PChar =
  (
    'No error',
    'File not found',
    'Out of memory',
    'Exit program?'
    // other error messages...
    );

  csMessages_DetailedVersion: array[Low(cnMessageIDs)..High(cnMessageIDs)]
  of PChar =
    (
    'No error; please ignore!',

    'File c:\config.sys not found.' +
    'Contact your sys. admin.',

    'Out of memory. You need ' +
    'at least 4M for this function',

    'Exit program? ' +
    'Save your data first!'
    // other error messages...
    );

procedure MsgDisplay(
  cnMessageID: cnMessageIDs);
begin
  // set this to False to display
  // short version of the messages
  if (True) then
    Application.MessageBox(csMessages_DetailedVersion[cnMessageID], 'Error', mb_OK)
  else
    Application.MessageBox(csMessages_ShortVersion[cnMessageID], 'Error', mb_OK);
end;

Now, whenever you want to display an error message, you can call the MsgDisplay() function with the message ID rather than typing the message itself:

MsgDisplay(nMsgID_FileNotFound);

MsgDisplay() function will not only let you keep all your error messages in one place -- inside one unit for example, but it will also let you keep different sets of error messages -- novice/expert, debug/release, and even different sets for different languages.

2004. június 10., csütörtök

Function to Populate a column of the DBGrid PickList so as to facilitate easy data entry in a grid


Problem/Question/Abstract:

A function to populate the DBGrid PickList to have auto selection of added field value when the grid is used to display a table

Answer:

The PickList of a DBGrid can be made useful for data entry through a dbgrid. This can be accomplished by the following function.Whenever a new entry is added to a particular field, that too can be made to appear in the picklist with the function given below.The PopulatePickList function can be called within DataSource.OnDataChange event so that it gets updated whenever a new entry is added.

procedure PopulatePickList(Column: TColumn; Table: TTable; FieldName: string);
var
  QryTemp: TQuery;
  i: integer;
begin
  Column.PickList.Clear;
  QryTemp := TQuery.Create(nil);
  with QryTemp do
  begin
    DatabaseName := Table.DatabaseName;
    SQL.Clear;
    SQL.Add('SELECT DISTINCT ' + FieldName + ' from ' + Table.TableName);
  end;

  with QryTemp do
  begin
    Active := True;
    First;
    for i := 0 to QryTemp.RecordCount - 1 do
    begin
      if FieldByName(FieldName).AsString <> '' then
        Column.PickList.Add(FieldByName(FieldName).AsString);
      Next;
    end;
    Active := False;
  end;
  QryTemp.Free;
end;

procedure TForm1.DataSourceDataChange(Sender: TObject; Field: TField);
begin
  PopulatePickList(DBGrid.Columns[2], Table, 'Field');
  //replace table with your tableName of the grid
  //DBGrid.Columns[2] with your DBGrid Column that you want the PickList for
  //Field with the field for the PickList
end;

2004. június 9., szerda

Track the mouse position over a TPanel on a form


Problem/Question/Abstract:

I want to track the position of the mouse over a TPanel within the client area of my main form. Using WM_MOUSEMOVE, I can track the mouse position over the main form easily enough, but once the mouse moves over my panel, the tracking stops. What do I need to do to track the position of the mouse over the panel?

Answer:

This is happening because TPanel is a different window with a handle of its own. You need to intercept the WM_MOUSEMOVE message in the TPanels WindowProc procedure. Assuming the form is TForm1 and the panel is Panel1:

First declare the following in the forms class:

private
{ Private declarations }
OldPanelWndProc: TWndMethod;

procedure NewPanelWndProc(var Message: TMessage);

Finally, implement the relevant code. Note how you should always call the old WindowProc procedure after you've handled the message. Also, WindowProc should be restored to it's original procedure when the form (containing the panel) is hidden. It would be a bad idea to restore the WindowProc procedure in the forms OnDestroy event because if it (the form) is hidden and shown again, it's going to cause problems with WindowProc being reassigned when it shouldn't be.

procedure TForm1.FormShow(Sender: TObject);
begin
  OldPanelWndProc := Panel1.WindowProc;
  Panel1.WindowProc := NewPanelWndProc;
end;

procedure TForm1.FormHide(Sender: TObject);
begin
  Panel1.WindowProc := OldPanelWndProc;
end;

procedure TForm1.NewPanelWndProc(var Message: TMessage);
begin
  case Message.Msg of
    WM_MOUSEMOVE:
      Caption := 'x = ' + inttostr(Message.LParamLo) + ' y = ' +
                         inttostr(Message.LParamHi);
  end;
  OldPanelWndProc(Message);
end;

2004. június 8., kedd

Managing a Single Instance of a Non-Modal Form


Problem/Question/Abstract:

How to manage the application's non-modal forms properly - to make sure that only one instance of a form is present at any given time, like it is done automatically for modal forms?

Answer:

When you have a modal form, you create, display and destroy it usually in a single uninterrupted sequence of code instructions, therefore it is easy to ensure that your form variable is equal to NIL after the form is expired, so you easily eliminate the risk of creating the same form twice or, even worse, attempting to access non-existing form when the only form's remains you actually have is the form variable with non-NIL value in it.

The problem with non-modal forms is that you usually create and display them in one place, then do whatever you want with your application (and not only that form), and order them to destroy themselves when they are no longer needed at any time - you cannot say beforehand where and when that will happen.
It is natural to close and free such a non-modal form from itself, but where to put clean-up instructions then? Without them, the application cannot know whether the form is alive - it relies merely on the form variable value (is it equal to NIL?) to determine if the form is still around. It is possible to introduce some application-level flags to keep track of the forms presence, but it is not an elegant solution.

Fortunately, as almost always with Delphi, there is a clear way to solve the problem.

Suppose you have frmNonModal as a form variable of TfrmNonModal class.

The procedure is simple:

   1. Add the following OnDestroy event handler to the form:

procedure TfrmNonModal.FormDestroy(Sender: TObject);
begin
  frmNonModal := nil;
  inherited;
end; {TfrmNonModal.FormDestroy}

Note that you cannot substitute frmNonModal with Self, though it seems to be the same from the first glance. The difference is that Self points to the object itself (and we don't want to nullify it prematurely), and frmNonModal is just an external (to the object) variable, which points to the object. By setting this variable to NIL we do not affect any internal functionality of the object, but rather just disconnect its link to the outer world. In our case this is exactly what we need, as we plan to check this variable when creating the form, as shown below.  

   2. Add the following OnClose event handler to the form:

procedure TfrmNonModal.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  inherited;
  Action := caFree;
end; {TfrmNonModal.FormClose}

This is needed to instruct our form to free itself when we close it. Note that by default Action is caHide, i.e. your form is just being closed (hidden), but not destroyed after calling TForm.Close.
  
   3. Bring your form to life as follows, for example in the menu item's OnClick event handler on your main form (of TfrmMain class):

procedure TfrmMain.itmNonModalFormClick(Sender: TObject);
begin
  if Assigned(frmNonModal) then
  begin
    {if the form already exists, just bring it to the front}
    frmNonModal.Show;
    frmNonModal.WindowState := wsNormal;
    frmNonModal.BringToFront;
  end
  else
  begin
    {create the form if it does not exist}
    frmNonModal := TfrmNonModal.Create(Application);
    try
      {display as non-modal form}
      frmNonModal.Show;
    except
      {clean up the form and form variable if unsuccessful}
      FreeAndNil(frmNonModal);
    end; {try}
  end; {if}
end; {TfrmMain.itmNonModalFormClick}

That's it. Now your application always knows whether your non-modal form is present (created), and manages to allow not more than a single instance of such form at a time.

2004. június 7., hétfő

How to resize open forms automatically when the Desktop size changes


Problem/Question/Abstract:

I have created a form which is snapped to the top of the screen. When I change the size of the Windows Desktop, the visible form isn't resized accordingly.

Answer:

I use the following code and it works quite good, even if the desktop size is changed:

type
  TForm1 = class(TForm)
  private
    procedure WMWindowPosChanging(var Message: TWMWindowPosMsg);
      message WM_WINDOWPOSCHANGING;

    { ... }

implementation

{ ... }

var
  WorkAreaRect: TRect;
  NewWorkAreaFlag: Boolean;

  { ... }

procedure TForm1.WMWindowPosChanging(var Message: TWMWindowPosMsg);
begin
  if (WindowState <> wsMaximized) then
  begin
    if (Message.WindowPos.Flags and SWP_NOMOVE) = 0 then
    begin {form is moved}
      if NewWorkAreaFlag then
      begin {workarea might have changed since last call}
        SystemParametersInfo(SPI_GETWORKAREA, 0, @WorkAreaRect, 0);
      end;
      {snap form to border here, something
                        like Message.WindowPos.X := WorkAreaRect.Left if near to left border}
      { ... }
    end;
    NewWorkAreaFlag := ((Message.WindowPos.Flags and (SWP_NOMOVE or SWP_NOSIZE)) <>
      0);
    {True if form was (probably) dropped => get workarea again}
  end;
end;

{ ... }

initialization
  NewWorkAreaFlag := True;

2004. június 6., vasárnap

Splitting a string in a string list


Problem/Question/Abstract:

A function that splits a string in parts separated by a substring and returns the parts in a StringList

Answer:

Solve 1:

The following functions split a string in parts separated by a substring and return the parts in a string list that may be passed as third parameter or created by the function (and in this latter case it must be freed by the caller):

interface

uses classes;

function SplitStrings(const str: string;
  const separator: string = ',';
  Strings: TStrings = nil): TStrings;
function AnsiSplitStrings(const str: string;
  const separator: string = ',';
  Strings: TStrings = nil): TStrings;

implementation

uses sysutils;

function SplitStrings(const str: string; const separator: string;
  Strings: TStrings): TStrings;
// Fills a string list with the parts of "str" separated by
// "separator". If Nil is passed instead of a string list,
// the function creates a TStringList object which has to
// be freed by the caller
var
  n: integer;
  p, q, s: PChar;
  item: string;
begin
  if Strings = nil then
    Result := TStringList.Create
  else
    Result := Strings;
  try
    p := PChar(str);
    s := PChar(separator);
    n := Length(separator);
    repeat
      q := StrPos(p, s);
      if q = nil then
        q := StrScan(p, #0);
      SetString(item, p, q - p);
      Result.Add(item);
      p := q + n;
    until q^ = #0;
  except
    item := '';
    if Strings = nil then
      Result.Free;
    raise;
  end;
end;

function AnsiSplitStrings(const str: string; const separator: string;
  Strings: TStrings): TStrings;
// Fills a string list with the parts of "str" separated by
// "separator". If Nil is passed instead of a string list,
// the function creates a TStringList object which has to
// be freed by the caller
// ANSI version
var
  n: integer;
  p, q, s: PChar;
  item: string;
begin
  if Strings = nil then
    Result := TStringList.Create
  else
    Result := Strings;
  try
    p := PChar(str);
    s := PChar(separator);
    n := Length(separator);
    repeat
      q := AnsiStrPos(p, s);
      if q = nil then
        q := AnsiStrScan(p, #0);
      SetString(item, p, q - p);
      Result.Add(item);
      p := q + n;
    until q^ = #0;
  except
    item := '';
    if Strings = nil then
      Result.Free;
    raise;
  end;
end;

Examples:

procedure TForm1.Button1Click(Sender: TObject);
begin
  SplitStrings(Edit1.Text, ', ', ListBox1.Items);
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  Parts: TStrings;
begin
  Parts := nil;
  try
    Parts := SplitStrings(Edit1.Text, ', ');
    ShowMessage('First part is "' + Parts[0] + '"');
  finally
    Parts.Free;
  end;
end;

You can see an example using a dynamic array instead of a StringList in a separate article "Splitting a string in an dynamic array".


Solve 2:

Shorten way:

function SplitStrings(const str: string; const separator: string;
  Strings: TStrings): TStrings;
// Fills a string list with the parts of "str" separated by
// "separator". If Nil is passed instead of a string list,
// the function creates a TStringList object which has to
// be freed by the caller
begin
  if Strings = nil then
    Result := TStringList.Create
  else
    Result := Strings;

  //This replaces the separators in str with CRLF so as to fit the format  of a stringlist.
  Result.Text := StringReplace(str, separator, #13#10, [rfReplaceAll]);
end;

2004. június 5., szombat

How to read the color of a pixel


Problem/Question/Abstract:

I need to determine if certain portions of my canvas are black. While this seemed easy enough at first, I'm at a roadblock trying to determine pixel color. As I usually do, I wrote a little test program and painted a certain area black. I tried the following code to read a pixel in that area:

if Canvas.Pixels[444, 399] = clBlack then
  MessageBeep(mb_ok);

I never get the beep. What am I doing wrong, and what would be the correct way to do this.

Answer:

Are you shure you hit the right pixel ? Try


canvas.pixels[444, 399] = clBlack
if canvas.pixels[444, 399] = clBlack then
  MessageBeep(mb_ok);


Windows converts colors (at least if you are using less than 24 bit screen mode). But black should exists on all palettes, I think. The color value of a pixel will be a DWORD (32 bit), encoded like this:

$XXRRGGBB

where XX are return values (as far as I remember, it even tells you , if it had to convert a color here). So you could try something like

(color and $FFFFFF) = clBlack

to get the return value out or

= $000000

to be sure it not depends on clBlack .

If that doesn't work, let it write the pixel color to screen an compare to value of clBlack. If worst case , get R,G and B and check if (near to ) 0.

2004. június 4., péntek

Disable a form movement


Problem/Question/Abstract:

How can I disable the any form movement?

Answer:

Always I saw a question: how can I move a window by hit in any part of form?
But I never saw a reverse question: how to disable a movement.

type
  TyourForm = class(TForm)
  private
    { Private declarations }
    procedure WMNCHitTest(var Message: TWMNCHitTest); message WM_NCHITTEST;
  end;

procedure TyourForm.WMNCHitTest(var Message: TWMNCHitTest);
begin
  inherited;

  with Message do
    if Result = HTCAPTION then
      Result := HTNOWHERE;
end;

2004. június 3., csütörtök

Retrieve just 1 row from a table (SQL)


Problem/Question/Abstract:

How do i retrive just 1 row from a sql table

Answer:

found this nice sql-tip for ya::

you have 2 options:

- use TOP function in sql

-----start
SELECT TOP 1 * FROM myTable
-----end

- by setting the rowcount before selecting in sql

-----start
SET ROWCOUNT 1
SELECT * FROM myTable
-----end

Note: If you use SET ROWCOUNT and you have a batch of commands, make sure you SET ROWCOUNT immediately before the SELECT statement. If you SET ROWCOUNT before an UPDATE or DELETE it will limit the number of rows affected by those operations.

2004. június 2., szerda

How to switch focus to an existing instance of an application


Problem/Question/Abstract:

How can I switch focus to an existing instance of an application instead of creating a new instance (HPrevInst)?

Answer:

{usual stuff at the top of the project source file}

var
  hwnd: Word;
begin
  if hPrevInst = 0 then
  begin
    Application.CreateForm(TForm1, Form1);
    Application.Run;
  end
  else
  begin
    hwnd := FindWindow('TForm1', nil);
    if (not IsWindowVisible(hwnd)) then
    begin
      ShowWindow(hwnd, sw_ShowNormal);
      PostMessage(hwnd, wm_User, 0, 0);
    end
    else
      SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE or SWP_NOMOVE);
  end;
end.

in the form's PAS file add a message response function for the wm_User message.

{in the form declaration}
public

procedure WMUser(var msg: TMessage); message wm_User;

{in the implementation section}

procedure TForm1.WMUser(var msg: TMessage);
begin
  Application.Restore;
end;

2004. június 1., kedd

Streaming COM Objects as XML


Problem/Question/Abstract:

Streaming COM Objects as XML

Answer:

Introduction

When I was making my first COM objects I used to think that I could give my COM classes the same shape of regular Delphi ones. I am specifically talking about properties and a "stateful life-style" in which you keep using its methods similarily to what you'd do with a DataSet (i.e. Open, Next, Next, Close). Well yes, COM allows you to do that and if the objects lives on the client's computer everything works fast and efficiently. The problem araises if and when you move your object to another machine. In that situation then your application suddenly starts to slow down and your client becomes dependent on the network condition. Each time you access a property you are invoking a method that executes on another machine. If your code makes such calls continuosly you will be in big trouble. The ideal solution would be to redesign such objects making them "stateless". With "stateless object" I mean those whose methods do all they say they will do (i.e. ExecuteMoneyTransfer) and don't depend on other methods (i.e. ExecuteMoneyTransfer doesn't expect a Commit or Rollback method to be called by the client after it is completion). But often the amount of legacy code makes a resedign not practical. Is it possible then to do anything to improve performance and makes stateful objects stateless? As you would expect it is possible (no point in writing this article otherwise ;-) ). By persisting the object's state in some kind of intermediary format (I choose XML) and streaming it in one shot you can achieve the goal. Remember that this is not an optimal solution and the code I am presenting here is not optimized either. If you are starting from scratch you should design stateless objects.

TlbInf32.dll

Included in Visual Studio 6 and Visual Basic 6.0 CDs you can find a very handy DLL called TlbInf32. You can download the documentation for this file on the MSDN webside. If you don't have Visual Studio you can download the DLL from the website Compiled.org

TlbInf32 includes a set of classes that can help you reading type information for both type libaries and COM objects. Now, download my example by clicking here.

The code

The example is very straightforward. I won't spend too much time on it. There's a simple COM library with an object which implements the following interface:

ISimpleObject = interface(IDispatch)
  function Name: WideString[propget, dispid $00000001]; safecall;
  procedure Name(Value: WideString)[propput, dispid $00000001]; safecall;
  function Age: Integer[propget, dispid $00000002]; safecall;
  procedure Age(Value: Integer)[propput, dispid $00000002]; safecall;
end;

Then there's a client application that is able to persist and restore the state of it by using an auxiliary class called TTypeInfoStreamer which is defined as:

TTypeInfoStreamer = class
private
  fTLI: _TLIApplication;
public
  constructor Create;

  function GetObjectAsXML(const anObject: IDispatch): widestring;
  procedure SetObjectAsXML(const anObject: IDispatch; aString: widestring);
end;

The two methods GetObjectAsXML and SetObjectAsXMl are what interest us. Please, don't make an example of the code. I put this sample togheter in 10 minutes to answer a question of a guy in a newsgroup. Take a look at the lines I highlighted:

function TTypeInfoStreamer.GetObjectAsXML(const anObject: IDispatch): widestring;
var
  xml: DOMDocument30;
  intfinfo: InterfaceInfo;
  root,
    node: IXMLDOMNode;
  i: integer;
  val: OleVariant;
  p: PSafeArray;
begin
  p := MakeEmptyParmsArray;

  try
    intfinfo := fTLI.InterfaceInfoFromObject(anObject);

    xml := CoDOMDocument30.Create;
    xml.async := FALSE;

    root := xml.createNode('element', intfinfo.Get_Name, '');
    xml.appendChild(root);

    with intfinfo do
      for i := 1 to (Members.Count) do
      begin
        if not (Members[i].InvokeKind = INVOKE_PROPERTYGET) then
          Continue;

        val := fTLI.InvokeHook(anObject, Members[i].Get_MemberId, INVOKE_PROPERTYGET,
          p);

        node := xml.createNode('element', Members[i].Name, '');
        node.text := VarToStr(val);
        root.appendChild(node);
      end;

  finally
    result := root.xml;
    SafeArrayDestroy(p);
  end;
end;

As you can see we created an instance of the TLIApplication object (included in TlbInf32.dll), passed a pointer to the object we want to stream and then looped tough its Members collections. The members collection is the list of methods implemented by the object. What we want to read is the value of the object's properties so we will only stop on the methods that return the value of a property (Members[i].InvokeKind=INVOKE_PROPERTYGET) . In order to invoke the method we need to call the method TLIApplication.InvokeHook which is defined as:

function InvokeHook(const Object_: IDispatch; ID: OleVariant; InvokeKind: InvokeKinds;
  var ReverseArgList: PSafeArray): OleVariant; safecall;

It's interesting to note how the ID parameter could be either the name of the method or its DispID. So, in case you have the DispID already, you wouldn't need to use late bound calls (which first invoke the IDispatch.GetIDOfNames method slowing things down a *lot*). InvokeKind tells the TLIApplication *how* to invoke it and finally the ReverseArgList is a safe array that in our case only contains no values. See the rest of the code to find out how I build one. The result is something like this:

<ISimpleObject>
  <Name>Alessandro Federici</Name>
  <Age>25</Age>
</ISimpleObject>

Et voila'! We have our COM object persisted into XML! Now we need to set back these values. See the code below.

procedure TTypeInfoStreamer.SetObjectAsXML(const anObject: IDispatch;
  aString: widestring);
var
  xml: DOMDocument30;
  intfinfo: InterfaceInfo;
  root,
    node: IXMLDOMNode;
  i: integer;
  val: OleVariant;
  p: PSafeArray;
  s: string;
begin
  p := MakeOneElementArray;

  try
    intfinfo := fTLI.InterfaceInfoFromObject(anObject);

    xml := CoDOMDocument30.Create;
    xml.async := FALSE;
    xml.loadXML(aString);
    root := xml.documentElement;

    with root do
      for i := 0 to (childNodes.length - 1) do
      begin
        s := childNodes[i].nodeName;
        SetOneElementArray(p, childNodes[i].Text);
        fTLI.InvokeHook(anObject, s, INVOKE_PROPERTYPUT, p);
      end;

  finally
    SafeArrayDestroy(p);
  end;
end;

As you can see we did the exact opposite of what the had done before except that in this case we invoked the method as a property writer. I hope this will demistify a little how to read COM type information and stream its contents in an arbitraty format. The TTypeInfoStreamer class is far from being a complete class but feel free to use the code as a start. Happy coding!

2004. május 31., hétfő

Select or find a TTreeView node by caption


Problem/Question/Abstract:

How to select or find a TTreeView node by caption

Answer:

Solve 1:

function GetNodeByCaption(NodeCaption: string): TTreeNode;
var
  X: Integer;
begin
  Result := nil;
  for X := 0 to TreeView1.Items.Count - 1 do
  begin
    if (TreeView1.Items[X].Caption = NodeCaption) then
      Result := TreeView1.Items[X];
    Break;
  end;
end;


Solve 2:

Returns a node based on the text property. Set AVisible to show the new node:

function GetNodeByText(ATree: TTreeView; AValue: string;
  AVisible: Boolean): TTreeNode;
var
  Node: TTreeNode;
begin
  Result := nil;
  if ATree.Count = 0 then
    Exit;
  Node := ATree.Items[0];
  while Node <> nil do
  begin
    if UpperCase(Node.Text) = AValue then
    begin
      Result := Node;
      if AVisible then
        Result.MakeVisible;
      Break;
    end;
    Node := Node.GetNext;
  end;
end;

2004. május 30., vasárnap

How to copy a 2D array with picture greylevels to an image (2)


Problem/Question/Abstract:

I have been developing a program to display and manipulate medical images which consist of 2D arrays of greyscale values as described. As was observed, the Pixels property is way too slow. Here's what I discovered. I think you'll find it a big improvement.

Answer:

Assuming your data is stored in an array of bytes named TestArray, for example:


TestArray: array[0..127, 0..127] of byte { ... }

ArrayPtr := addr(TestArray); {ArrayPtr: pointer}


In this case we are going to display on the bitmap of a TImage component that has been dropped on the canvas and named Image1.


Image1.Picture.Bitmap.Width := 128;
Image1.Picture.Bitmap.Height := 128;


This is a Windows API function that will copy the bits in TestArray, pointed to by ArrayPtr, into an HBitmap structure, in this case Image1.Picture.Bitmap.Handle.


SetBitmapBits(Image1.Picture.Bitmap.Handle, sizeof(TestArray), ArrayPtr);
Image1.Refresh; {must refresh before changes are displayed}


You still have to deal with the palette, but this technique works great for me.

2004. május 29., szombat

How to set the DisplayFormat of a TDateTime field to time only at runtime


Problem/Question/Abstract:

I'm running a simple query that returns a variable amount of columns somtimes with a DateTime column. How can I set at runtime the Displayformat property or any other way to format the column as a time only field. In other words, I can't seem to find where to set the DisplayFormat property at runtime.

Answer:

Here's one way:

procedure FormatDateFieldsAsTime(DS: TDataSet; TimeFormat: string);
var
  f: integer;
begin
  for f := 0 to DS.FieldCount - 1 do
    if DS.Fields[f] is TDateTimeField then
      TDateTimeField(DS.Fields[f]).DisplayFormat := TimeFormat;
end;

Apply this to the query after it's been run, like:

FormatDateFieldsAsTime(Query1, 'hh:mm:ss');

The DisplayFormat is available (assuming you're not creating any persistant fields for this dynamic query) from the query's (or other TDataSet's) Fields property.