I have a Listbox with different numbers that can be added at any time through a TEdit.
How can I take each item from the listbox and just simply add them to get a Total Amount.

For example.. Say My Listbox looks like this:
14.00
2.00
7.00
13.00

how do I add those 4 numbers together? It has to be in a way so that if I add a Fifth item, it'll include that too.

Please help!

Thank you.

Recommended Answers

All 5 Replies

Use a loop:

var
  total: double;
  cntr: integer;
begin
  total := 0.0;
  for cntr := 0 to ListBox1.items.count -1 do
    total := total +strToFloat( ListBox1.items[ cntr ] );
  showMessage( 'The total is ' +floatToStr( total ) )
end;

Use a loop:

var
  total: double;
  cntr: integer;
begin
  total := 0.0;
  for cntr := 0 to ListBox1.items.count -1 do
    total := total +strToFloat( ListBox1.items[ cntr ] );
  showMessage( 'The total is ' +floatToStr( total ) )
end;

Might I suggest two changes

  • Rather than doing ListBox1.items inside the loop, just store a reference as AList:=ListBox1.Items and use that.
  • strToFloat will trigger an exception if the ListBox entry is not numeric. There are two solutions - a. Use StrToFloatDef, b. wrap the loop in a try..except block and show an error message

Rather than doing ListBox1.items inside the loop, just store a reference as AList:=ListBox1.Items and use that.

You could also use a with statement. In this particular case it all comes down personal preference, as the compiler will do the same thing either way... If I only have to type it once or twice I personally find it more unwieldy to type in a temp.

strToFloat will trigger an exception if the ListBox entry is not numeric. There are two solutions - a. Use StrToFloatDef, b. wrap the loop in a try..except block and show an error message

As for the exception, that is intentional. If the list is not composed entirely of stringified floats then it cannot be summed. (Two plus green apple makes no sense.) Hence, the exception.

However, I should have said something about the exception. (I just assumed that the OP would notice that --my bad.)

In general, exceptions should not be bound into the code that may generate them, but at an "operational boundary" (as I will call it). That is, permit exceptions to unwind as far back as is reasonable. In the case of an OnClick event procedure, a user-input error should be bound to the outermost block of the procedure itself:

procedure MyForm.SumButtonClick( Sender: TObject );
  var total: double;
  begin
  try
    total := SumListBox1;
    showMessage( 'The total is ' +floatToStr( total ) )
  except
    on EConvertError do begin
      ShowMessage(
        'All the items must be numbers if you want to add them.'
        );
      ListBox1.setFocus
      end
  end
  end;

The only exception I catch here is the only one that is both not fatal and entirely possible due to bad user input. Other exceptions continue to unwind. Since bad input is always possible, the user is informed of his error, the offending listbox is focused, and execution continues normally.

Hope this helps.

You could also use a with statement. In this particular case it all comes down personal preference, as the compiler will do the same thing either way... If I only have to type it once or twice I personally find it more unwieldy to type in a temp.


As for the exception, that is intentional. If the list is not composed entirely of stringified floats then it cannot be summed. (Two plus green apple makes no sense.) Hence, the exception.

However, I should have said something about the exception. (I just assumed that the OP would notice that --my bad.)

In general, exceptions should not be bound into the code that may generate them, but at an "operational boundary" (as I will call it). That is, permit exceptions to unwind as far back as is reasonable. In the case of an OnClick event procedure, a user-input error should be bound to the outermost block of the procedure itself:

procedure MyForm.SumButtonClick( Sender: TObject );
  var total: double;
  begin
  try
    total := SumListBox1;
    showMessage( 'The total is ' +floatToStr( total ) )
  except
    on EConvertError do begin
      ShowMessage(
        'All the items must be numbers if you want to add them.'
        );
      ListBox1.setFocus
      end
  end
  end;

The only exception I catch here is the only one that is both not fatal and entirely possible due to bad user input. Other exceptions continue to unwind. Since bad input is always possible, the user is informed of his error, the offending listbox is focused, and execution continues normally.

Hope this helps.

There are benefits in not having your code littered with multiple references such as ListBox1. To mention just three

  • More compact and readable
  • Less prone to typos - ok, the Delphi compiler does a good job of catching them but why not save time and minimize them in the first place?
  • So what happens when you finally decide to go from ListBox1 to lbNumbers or some other unified nomenclature? A Search & Replace to remove every refernce to ListBox1?

Now imagine a large project with tens of units each with 1000s of lines of code. Imagine all the time lost, the needlessly lengthy code...

Please stop going on the offensive for stylistic concerns. All four of your arguments fail:

  • It is less compact and less readable to introduce an alias for something when used but once or twice. Particularly when that alias is limited to a specific block.
  • Typos are just as likely to occur no matter what you do.
  • No one should be using "ListBox1" as a name. A careful nomenclature should start the very instant you drop a component on your form and name it properly. However, Delphi has its defaults, and examples on the net using the "ComponentType1" idiom are well-understood as representing any component of the referenced type, as opposed to some specific user's specifically named component of that type.
    It is true that both Delphi's defaults and the careless use of them on the net encourage bad naming practices, but naming practices are not the issue here, and proper naming from the start obviates the search and replace problem.
  • As for the tens of units with 1000s of lines of code... I've written larger projects than that, and never encountered any problem. Why? Specific components should always be private to the class in which they are declared. If foreign access is desirable, it should be specifically granted through the class's published properties, by which it is properly accessible no matter how stupid a name it may have internally.
    In other words, there should ever be but one unit in which a class's component is specifically referenced. If you do have occasion to change a component's name (which happens), the IDE's search and replace function is more than capable of doing it in one single step.

Finally, as to the original premise:
> There are benefits in not having your code littered with multiple references such as ListBox1
>
Aside from the bad name, it is impossible to refer to a specific component without specifically naming it. That is the purpose of its having a name and it is both wholly appropriate and entirely expected that the programmer should use that name as regularly as needed.


None of this has anything to do with the OP's question, and since we know almost nothing of his experience or coding preferences I feel it is little more than soapbox hobbying to continually introduce unrelated matter into the thread.

I'm sorry if I've offended you, but if I have then take it up in PM or just get over it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.