How to avoid “Type mismatch in expression” in ClientDataSet Filter

随声附和 提交于 2019-12-13 04:24:11

问题


The erro msg "Type mismatch in expression" appear when I run this code:

CDSIndicados.Filtered := False;
CDSIndicados.Filter   := 'EDICOES_ID like ' + QuotedStr(IntToStr(Integer(cxComboBox1.Properties.Items.Objects[cxComboBox1.ItemIndex])));
CDSIndicados.Filtered := True;

I know this message may appear when there is an error in the data type of the field. But I could not fix. Was that it?


回答1:


I'm suspecting that your EDICOES_ID field is an integer value, in which case you don't need to quote it in your filter expression and the LIKE operator isn't supported AFAIK. If it is a string field, you do need the quotes and LIKE is supported, but you typically want a wildcard in the expression as well. (LIKE is only supported for character (string) type fields. For numerics or dates, you need to use the usual comparison operators >, <, >=, <=, = or BETWEEN.)

Do yourself a favor, too, and declare a local variable, and making sure that there's actually an item selected in the ComboBox before trying to access its Objects. I've added one both for the ItemIndex and for intermediate storage of the typecast Object you're retrieving, which makes it much easier to debug if you need to do so.

Here's a solution either way (whether it's an integer field, or a string that needs quoting).

var
  Idx, Value: Integer;
begin
  Idx := ComboBox1.ItemIndex;
  if Idx > -1 then
  begin
    CDSIndicados.Filtered := False;
    Value := Integer(cxComboBox1.Properties.Items.Objects[Idx]);

    // If the field is an integer, you don't need a quoted value,
    // and LIKE isn't supported in the filter.
    CDSIndicados.Filter   := 'EDICOES_ID = ' +  IntToStr(Value);

    // Not relevant here, but LIKE isn't supported for date values
    // either. For those, use something like this
    CDSIndicados.Filter := 'EDICOES_DATE = ' + QuotedStr(DateToStr(Value));

    // or, if the field is string and you want LIKE, you need to
    // quote the value and include a wildcard inside that quoted 
    // string.
    CDSIndicados.Filter := 'EDICOES_ID LIKE ' + QuotedStr(IntToStr(Value) + '%');
    CDSIndicados.Filtered := True;
  end;
end;


来源:https://stackoverflow.com/questions/16780755/how-to-avoid-type-mismatch-in-expression-in-clientdataset-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!