Error when inserting sales line in table via C/AL

Following scenario: Sales Order Line. When selecting a custom line type (e.g. MyTest) another form is called, some calculations are made, and at the end the following code is executed: SalesLine.RESET; SalesLine.INIT; SalesLine.SETRANGE(“Document Type”,DefaSalesLine.“Document Type”); SalesLine.SETRANGE(“Document No.”,DefaSalesLine.“Document No.”); IF SalesLine.FIND(’+’) THEN NextLineNo := SalesLine.“Line No.” + 10000 ELSE NextLineNo := 10000; SalesLine.INIT; SalesLine.RESET; SalesLine.“Document No.” := DefaSalesLine.“Document No.”; SalesLine.VALIDATE(“Document Type”,DefaSalesLine.“Document Type”); SalesLine.“Line No.” := NextLineNo; SalesLine.Description := ‘Hallo’; SalesLine.INSERT; I would expect a line inserted with text “Hallo”. This only works, if I change the line type on the sales order subform without any empty lines above. If there is at least one empty line above (empty means not yet created in the database) the systems prompts an error “The Sales Lines already exists. Identification fields and values:…”. The the sales order form is closed. When reopened, the line with “Hallo” DOES EXIST!! It is important to mention, that no empty lines were respected (which appears normal looking at the calculation of “Line No.” := NextLineNo. Any idea why I keep getting that error? Is there a way to determine the current line number where I want to insert something, well knowing that the lines above do not exist in the db yet?! Thanks in advance.

Not reading your comments after code I can say that you need to change your code like this: SalesLine.RESET; SalesLine.SETRANGE("Document Type",DefaSalesLine."Document Type"); SalesLine.SETRANGE("Document No.",DefaSalesLine."Document No."); IF SalesLine.FIND('+') THEN NextLineNo := SalesLine."Line No." + 10000 ELSE NextLineNo := 10000; SalesLine.INIT; SalesLine."Document No." := DefaSalesLine."Document No."; SalesLine.VALIDATE("Document Type",DefaSalesLine."Document Type"); SalesLine."Line No." := NextLineNo; SalesLine.Description := 'Hallo'; SalesLine.INSERT;

Sorry, same error. The system still says “The Sales Line already exists.” [?]

I think you are asking two things here… 1) Why do you get kicked out of the form? Your code looks ok here and the line is inserted, so i would guess that when you return from the function, you don’t refresh the form and then try to insert a new record via the form with the same key (Line No.). You should also save the current record before you call your function. One way to check this would be to temporarily change the NextLineNo calculation to add a number other than 10000 (use 5555 or something), to avoid the numbering from the AutoSplitKeys. 2) Why are the blank lines not respected? These blank lines are inserted by the form (MultipleNewLines property). There is no automatic way to do this via code. This functionality would have to be duplicated in your insert function if you wanted it.