Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

delphi - How to avoid "Type mismatch in expression" in ClientDataSet Filter

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...