Allowing Needed Updates

From RAD Studio
Jump to: navigation, search

Go Up to Making the Control Read-only


The read-only calendar uses the SelectCell method for all kinds of changes, including setting the Row and Col properties. The UpdateCalendar method sets Row and Col every time the date changes, but because SelectCell disallows changes, the selection remains in place, even though the date changes.

To get around this absolute prohibition on changes, you can add an internal Boolean flag to the calendar, and permit changes when that flag is set to True:

Delphi:

type
  TDBCalendar = class(TSampleCalendar)
  private
    FUpdating: Boolean;                                  { private flag for internal use }
  protected
    function SelectCell(ACol, ARow: Longint): Boolean; override;
  public
    procedure UpdateCalendar; override;                { remember the override directive }
  end;
  // …
function TDBCalendar.SelectCell(ACol, ARow: Longint): Boolean;
begin
  if (not FUpdating) and FReadOnly then Result := False       { allow select if updating }
  else Result := inherited SelectCell(ACol, ARow);     { otherwise, use inherited method }
end;
procedure TDBCalendar.UpdateCalendar;
begin
  FUpdating := True;                                         { set flag to allow updates }
  try
    inherited UpdateCalendar;                                          { update as usual }
  finally
    FUpdating := False;                                          { always clear the flag }
  end;
end;

C++:

class PACKAGE TDBCalendar : public TSampleCalendar
{
private:
    // …
    bool FUpdating;                                  // private flag for internal use
protected:
    virtual bool __fastcall SelectCell(long ACol, long ARow);
public:
    // …
    virtual void __fastcall UpdateCalendar();
    // …
};
bool __fastcall TDBCalendar::SelectCell(long ACol, long ARow)
{
    if (!FUpdating && FReadOnly) return false;          // can't select if read only
    return TSampleCalendar::SelectCell(ACol, ARow);     // otherwise, use inherited method
}
void __fastcall TDBCalendar::UpdateCalendar()
{
  FUpdating=true;                                     // set flag to allow updates
  try
  {
     TSampleCalendar::UpdateCalendar();              // update as usual
  }
  catch(...)
  {
    FUpdating = false;
    throw;
  }
  FUpdating = false;                                  // always clear the flag
}

The calendar still disallows user changes, but now correctly reflects changes made in the date by changing the date properties. Now that you have a true read-only calendar control, you are ready to add the data browsing ability.