Calc field doesn't post - delphi

Hi I want to post calc field(cemi) to table (sql). when I calc all field the last field doesn't post on sql table. because last field (cemi) type fkcalc how can I post fkcalc type field to sql table Thanks in advance!
procedure TForm1.ADOQuery1CalcFields(DataSet: TDataSet);
begin
ADOQuery1.FieldValues['cemi']:=
((ADOQuery1.FieldValues['boyuk1'] + ADOQuery1.FieldValues['boyuk2'] +
ADOQuery1.FieldValues['boyuk3'])*0.35)+((ADOQuery1.FieldValues['kicik1'] +
ADOQuery1.FieldValues['kicik2'])*0.25) +(ADOQuery1.FieldValues['qara1']*0.30);
end;

I'm not quite sure what you mean by
the last field doesn't post on sql table
If the "last field" you are referring to is your "Cemi" one and that is a column which is in the table on your SQL Server, it will not get posted back there if you have defined it as a calculated field in your AdoQuery1 in the Object Inspector. Fields with a FieldKind of fkCalculated are local to the AdoQuery.
Just assigning a value to the calculated field is sufficient to "post" it locally to the AdoQuery, as I imagine you know. What you want to do to debug your problem (because readers like me cannot debug it fr you) is to more easily see what value, if any, is being assigned to it.
From that point of view, your code is suffering from "premature optimisation" which will make it difficult for you to see what is going wrong. Try this instead:
In your ADOQuery1CalcFields, declare a local variable for each of the fields you are accessing, including the calculated one. Choose the variable types to suit the fields:
var
Boyuk1 : Double; // or Integer, etc
[...]
Cemi : Double;
Assign values to the local variables, using the AsXXXX (type) of the fields:
Cemi := 0;
if not AdoQuery1.FieldByName('Boyuk1').IsNull then
Cemi := Cemi + AdoQuery1.FieldByName('Boyuk1').AsFloat;
[etc]
That way, at least you'll be able to see the point at which the calculation goes wrong (if it does).
I've used FieldByName().AsFloat, rather than FieldValues[], because FieldValues[] is a Variant, which can be Null, and you don't want that when you are assigning values to it which mat themselves be variants.
Also
Check that AutoCalcFields is set to True for AdoQuery1.
Put a debugger breakpoint on the first line of ADOQuery1CalcFields. Compile and run and check that the breakpoint hits - if it doesn't, there's your answer. Single-step the debugger through each line of the procedure, and, after the final line, use Ctrl-F7 to evaluate the value of AdoQuery1.FieldByName('Cemi').AsFloat.

Related

Filtering a TTable Where The FieldName Contains a Space [duplicate]

I am using Delphi, but this is a simple and general problem:
I'm doing the following:
var
ArticlesTable: TADOTable;
begin
ArticlesTable.DisableControls;
ArticlesTable.Sort := 'CITY';
ArticlesTable.First;
while not ArticlesTable.Eof do begin
...
ArticlesTable.Next;
end;
This works very well and allows me to efficiently process the records one by one with the records ordered ascending by the CITY field as they are coming in.
However, now I wanted to order by the field "LAST NAME" which has an embedded space in it. But when I use the statement:
ArticlesTable.Sort := 'CITY';
I get the error message:
EOleException: Arguments are of the wrong type, are out of acceptable range,
or are in conflict with one another.
I have seen the help on the SORT string syntax. It says to separate multiple fields by commas, and to add ASC or DESC after a field to sort ascending or descending. But it doesn't say what to do if a fieldname has a space in it.
I've tried putting the field name in single and double quotes and even using #20 as the space character, but those don't work.
I can't change the field name on the Microsoft Access database, because there are other programs I don't work with that depend on it.
I'm sure there must be an easy way to do this that I don't know about.
Have you tried surrounding the fieldname by square brackets? for example:
ArticlesTable.Sort := '[LAST NAME]';

cxGrid calculate as you type

Simplified I have a cxGrid where I type a start time and a end time. What I need is a function that when I change one of these values calculates the difference and stores this in a third column
I am having trouble finding the correct way of doing this.
I guess you have assigned some sort of Properties editor (probably a DateEdit) to the column.
Given that, you could try to use following code in the OnValidate event of the Properties editor:
var
ValueThirdCol : variant;
RecordIndex : integer;
begin
RecordIndex := myView.DataController.FocusedRecordIndex;
ValueThirdCol := myView.DataController.GetValue(RecordIndex, MyEndDateCol.Index) - myView.DataController.GetValue(RecordIndex, MyStartDateCol.Index);
myView.DataController.SetValue(RecordIndex, myDifCol.Index, ValueThirdCol);
end;
Please note that you might have to tweak this code a bit depending on if you have set GridMode or DataModeController.SyncMode to true, or not, and to use DisplayValue where necessary, but the basic idea should work.
EDIT: the OnValidate event of the Properties editor occurs before converting the display value to the edit value. That is the reason why this code I provided had to be tweaked.
In order for the code to work, you need to use (for the column being modified) the DisplayValue argument provided by the event instead of the value returned by GetValue.
For example, if the EndDateCol would be the column that triggered the OnValidate, then the code should be
ValueThirdCol := DisplayValue - myView.DataController.GetValue(RecordIndex, MyStartDateCol.Index);
HTH

Dbgrid calculation

I have a DBGrid and I´m trying to do a billing sheet but sometimes it doesn't do the calculations. How can I avoid that??
procedure TOrcamentos.DBGridEh1ColExit(Sender: TObject);
var
percent: double;
Unid: double;
tot: currency;
vaz: string;
begin
if Dorcamen_SUB.DataSet.State in [dsEdit, dsInsert] then
try
Dorcamen_SUB.DataSet.Post;
finally
vaz := DBGridEh1.Columns[3].Field.text;
if (vaz<> '') then
try
Torcamen_SUB.Edit;
Unid := (Torcamen_SUB.FieldByName('QT').AsFloat);
tot := (Torcamen_SUB.FieldByName('Precovenda').AsFloat);
percent := (Torcamen_SUB.FieldByName('Desconto').AsFloat);
try
tot := tot+(tot * percent)/ 100;
finally
Torcamen_SUB.FieldByName('Total').AsFloat := unid*tot;
Torcamen_SUB.Post;
Orcamentos.TotalExecute(self);
end;
except
end;
end;
end;
The better way to implement calculations is actually to move the calculation to your TTable component that the grid is linked to. The Total field shouldn't actually be a field in the database since but rather a calculated field based on values from other fields. Simply add an extra field using the field editor of the table, type in the field name Total, select the correct datatype and then select the field type as Calculated. Click Ok and then add code similar to this for the OnCalcField event of the table:
Torcamen_SUB.FieldByName('Total').AsFloat := Torcamen_SUB.FieldByName('QT').AsFloat * (
Torcamen_SUB.FieldByName('Precovenda').AsFloat + (Torcamen_SUB.FieldByName('Precovenda').AsFloat * Torcamen_SUB.FieldByName('Desconto').AsFloat)/100) ;
A general rule of thumb is that calculated values shouldn't be saved to the database unless really really necessary. It's best to simply add them as calculated fields to the dataset and then link the grid to the dataset. All calculated fields will then be displayed in the grid and each row will show the correct calculated value based on the values for that row.
I think you're mixing a business logic (like calculating a total) with User Interaction logic (like the event on which some grid column loses the focus) and that's the source of the erratic behavior of your application.
Looks like not even you know where it happens and where it doesn't happen.
Consider using the Field's events (for example, OnChange event) to perform that kind of calculations.
Lucky you if you're using a dataset with aggregation capabilities (like TClientDataSet), because you can just declare what you want in a TAggregateField and forget about doing calculations "by hand".
Not your question but... be careful with the way you're using try/finally also... for example, in this bit of code:
try
tot := tot+(tot * percent)/ 100;
finally
Torcamen_SUB.FieldByName('Total').AsFloat := unid*tot;
//other things
end;
be aware that if for some reason an exception occurs on the line between the try and finally clauses, the variable tot will have an undefined value (in this case, the result of the previous assignment), so the Assignment to the Torcamen_SUB.total field will be wrong, after all. I'm not sure if it is really what you want.

Sorting a table physically in Delphi

Delphi does not seem to like multi-field indexes.
How do I physically sort a a table so that I wind up with a table that has the rows in the desired order?
Example:
mytable.dbf
Field Field-Name Field-Type Size
0 Payer Character 35
1 Payee Character 35
2 PayDate Date
3 Amount Currency
I need to produce a table sorted alphabetically by "Payee"+"Payer"
When I tried using an index of "Payee+Payer", I got an error:
"Field Index out of range"
The index field names need to be separated by semicolons, not plus symbols. Try that and it should work.
Ok, let's try to put some order.
First, isn't advisable to physically sort a table. In fact the most RDBMS even don't provide you this feature. Usually, one, in order to not force a full table scan (it is called sometimes natural scan) creates indexes on the table fields on which he thinks that the table will be sorted / searched.
As you see, the first step in order to sort a table is usually index creation. This is a separate step, it is done once, usually at, let's say, "design time". After this, the DB engine will take care to automatically update the indexes.
The index creation is done by you (the developer) using (usually) not Delphi (or any other development tool) but the admin tool of your RDBMS (the same tool which you used when you created your table).
If your 'DB engine' is, in fact, a Delphi memory dataset (TClientDataSet) then you will go to IndexDefs property, open it, add a new index and set the properties there accordingly. The interesting property in our discussion is Fields. Set it to Payee;Payer. Set also the Name to eg. "idxPayee". If you use other TDataSet descendant, consult the docs of your DB engine or ask another question here on SO.com providing the details.
Now, to use the index. (IOW, to sort the table, as you say). In your program (either at design time either at run time) set in your 'Table' the IndexName to "idxPayee" or any other valid name you gave or set IndexFieldNames to Payee;Payer.
Note once again that the above is an example based on TClientDataSet. What you must retain from the above (if you don't use it) is that you must have an already created index in order to use it.
Also, to answer at your question, yes, there are some 'table' types (TDataSet descendants in Delphi terminology) which support sorting, either via a Sort method (or the like) either via a SortFields property.
But nowadays usually when one works with a SQL backend, the preferred solution is to create the indexes using the corresponding admin tool and then issue (using Delphi) an SELECT * FROM myTable ORDER BY Field1.
HTH
If you're still using BDE you can use the BDE API to physically sort the DBF table:
uses
DbiProcs, DbiTypes, DBIErrs;
procedure SortTable(Table: TTable; const FieldNums: array of Word; CaseInsensitive: Boolean = False; Descending: Boolean = False);
var
DBHandle: hDBIDb;
RecordCount: Integer;
Order: SORTOrder;
begin
if Length(FieldNums) = 0 then
Exit;
Table.Open;
RecordCount := Table.RecordCount;
if RecordCount = 0 then
Exit;
DBHandle := Table.DBHandle;
Table.Close;
if Descending then
Order := sortDESCEND
else
Order := sortASCEND;
Check(DbiSortTable(DBHandle, PAnsiChar(Table.TableName), nil, nil, nil, nil, nil,
Length(FieldNums), #FieldNums[0], #CaseInsensitive, #Order, nil, False, nil, RecordCount));
end;
for example, in your case:
SortTable(Table1, [2, 1]); // sort by Payee, Payer
Cannot check, but try IndexFieldNames = "Payee, Payer".
Sure indexes by these 2 fields should exist.
You can create an index on your table using the TTable.AddIndex method in one call. That will sort your data when you read it, that is if you use the new index by setting the TTable.IndexName property to the new index. Here's an example:
xTable.AddIndex('NewIndex','Field1;Field2',[ixCaseInsensitive]);
xTable.IndexName := 'NewIndex';
// Read the table from top to bottom
xTable.First;
while not xTable.EOF do begin
..
xTable.Next;
end;

How Can I Sort an ADO Table on a Fieldname Containing a Space?

I am using Delphi, but this is a simple and general problem:
I'm doing the following:
var
ArticlesTable: TADOTable;
begin
ArticlesTable.DisableControls;
ArticlesTable.Sort := 'CITY';
ArticlesTable.First;
while not ArticlesTable.Eof do begin
...
ArticlesTable.Next;
end;
This works very well and allows me to efficiently process the records one by one with the records ordered ascending by the CITY field as they are coming in.
However, now I wanted to order by the field "LAST NAME" which has an embedded space in it. But when I use the statement:
ArticlesTable.Sort := 'CITY';
I get the error message:
EOleException: Arguments are of the wrong type, are out of acceptable range,
or are in conflict with one another.
I have seen the help on the SORT string syntax. It says to separate multiple fields by commas, and to add ASC or DESC after a field to sort ascending or descending. But it doesn't say what to do if a fieldname has a space in it.
I've tried putting the field name in single and double quotes and even using #20 as the space character, but those don't work.
I can't change the field name on the Microsoft Access database, because there are other programs I don't work with that depend on it.
I'm sure there must be an easy way to do this that I don't know about.
Have you tried surrounding the fieldname by square brackets? for example:
ArticlesTable.Sort := '[LAST NAME]';

Resources