views:

113

answers:

2

Hi!

Here is a codesnippet I use to get filtertype operator from a filter in a DevExpress grid: OperatorKindToStr is used to extract operatorkind from a filter as string and store it in a xml-file. StrToOperatorKind is used to convert back a string from xml to set an operatorkind in a filter.

const
  CUSTFILTER_FILTERITEM     = 'FilterItem';

function OperatorKindToStr(const aOperatorKind: TcxFilterOperatorKind): string;
begin
  Result := 'foEqual';
  case aOperatorKind of
    foEqual:        Result := 'foEqual';
    foNotEqual:     Result := 'foNotEqual';
    foLess:         Result := 'foLess';
    foLessEqual:    Result := 'foLessEqual';

  // Plus a boring list of other constants
end;

function StrToOperatorKind(const aOpKindStr: string): TcxFilterOperatorKind;
begin
  Result := foEqual;
  if aOpKindStr       = 'foNotEqual' then
    Result := foNotEqual
  else if aOpKindStr  = 'foLess' then
    Result := foLess
  else if aOpKindStr  = 'foLessEqual' then
    Result := foLessEqual
  else if aOpKindStr  = 'foGreater' then
    Result := foGreater
  else if aOpKindStr  = 'foGreaterEqual' then
    Result := foGreaterEqual

  // Plus a boring list of other if-else
end;

procedure UseStrToOperatorKind(const aFilterItem: IXmlDomElement);
begin
  if aFilterItem.nodeName = CUSTFILTER_FILTERITEM then
  begin                              // It is an FilterItem
    vStr := VarToStr(aFilterItem.getAttribute(CUSTFILTER_COLPROP));  // Get the columnname
    vOperatorKind := StrToOperatorKind(aFilterItem.getAttribute(CUSTFILTER_ITEMOPERATOR));
end;

procedure UseOperatorKindToStr(const aFilterItem: TcxCustomFilterCriteriaItem);
var
  vStr: String;
begin
  if Supports(TcxFilterCriteriaItem(aFilterItem).ItemLink, TcxGridColumn, GridCol) then
    vStr := OperatorKindToStr(TcxFilterCriteriaItem(aFilterItem).OperatorKind);
end;

Apparently I want the StrToOperatorKind and OperatorKindToStr to be a bit smarter. I have tried GetEnumProp method in VCL TypeInfo but it won't work. So how can I extract the TcxFilterOperatorKind property from a aFilterItem variable to a string and back to a TcxFilterOperatorKind ?

+1  A: 

GetEnumProp didn't work because it's the wrong function for what you're trying to do. You're close, though. Try GetEnumName and GetEnumValue, which are also in the TypInfo unit.

Mason Wheeler
+1  A: 

Use the GetEnumName and GetEnumValue duet as Mason pointed out.

And your functions should become much simpler:

function OperatorKindToStr(const aOperatorKind: TcxFilterOperatorKind): string;
begin
  Result := GetEnumName(TypeInfo(TcxFilterOperatorKind), Ord(aOperatorKind));
end;

function StrToOperatorKind(const aOpKindStr: string): TcxFilterOperatorKind;
begin
  Result := TcxFilterOperatorKind(GetEnumValue(TypeInfo(TcxFilterOperatorKind), aOpKindStr));
end;
François
Yep! That was correct. Thanks for the advice.
Roland Bengtsson