Entwickler-Ecke

Dateizugriff - ListBox.Items in Datei speichern


Biarchiv - Fr 06.06.03 20:21
Titel: ListBox.Items in Datei speichern
Hallo,

Ich habe folgenden Code geschrieben.
Nur funktioniert das speichern nicht so ganz.

Ich will das der gesamte Inhalt der ListBox in eine Textdatei gespeichert wird

Delphi-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
procedure TForm1.Button2Click(Sender: TObject);
var i : integer;
  data : string;
  file1 : textfile;

label zur;
begin
i := 1;
assignfile(file1, ExtractFilePath(ParamStr(0)) + 'wtm.dat');//, file1);
Reset(file1);

zur:
i := i + 1;
data := ListBox1.items[i];
writeln(data);
If not (i = 500then goto zur;
//If not (ListBox1.items.count=-1) then goto zur;
CloseFile(file1);
end;


Danke

Moderiert von user profile iconTino: Code- durch Delphi-Tags ersetzt.


Christian S. - Fr 06.06.03 20:43

Hast Du Dir schon mal die Funktion ListBox.Items.SaveToFile angeschaut?

Und eine Schleife sollte man in Delphi nun wirklich nicht mit labels bewerkstelligen. Delphi hat da doch ganz andere Möglichkeiten!

Ach ja, demnächst bitte Delphi- statt Code-Tags verwenden!

MfG,
Peter


Tweafis - Fr 06.06.03 20:43

warum benutzt du nicht ListBox1.Items.SaveToFile?

// Edit: ARGH Immer komm ich zu spät ;)


Tino - Di 10.06.03 10:50

Hi,

der Fehler liegt wohl daran:

Delphi-Quelltext
1:
WriteLN (file1, data);                    

Du musst die Variable file1 angeben.

Peter Lustig hat folgendes geschrieben:
Delphi hat da doch ganz andere Möglichkeiten!

...zum Bespiel die For-Next-Schleife:

Delphi-Quelltext
1:
2:
For Idx := 0 To ListBox1.Items.Count -1 Do
  WriteLn (File1, ListBox1.Items [Idx]);


Gruß
Tino


Herbert - Di 10.06.03 11:22

Hi!

Du könntest die Items auch in einem Stream speichern.

Delphi-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
procedure SaveListBoxItems;
var Stream: TFileStream;
    i: Integer;
    LbItemLength: LongInt;
    LbCount: LongInt;
begin
  Stream := TFileStream.Create(ExtractFilePath(ParamStr(0)) + 'LB_Items.dat',
                                fmCreate);

  try
    LbCount := ListBox1.Count - 1;
    Stream.Write(LbCount, SizeOf(LbCount));

    For i := 0 to LbCount do
    begin
      LbItemLength := Length(ListBox1.Items[i]);
      Stream.Write(LbItemLength, SizeOf(LbItemLength));
      Stream.Write(PChar(ListBox1.Items[i])^, LbItemLength);
    end;
  finally
    Stream.Free;
  end;
end;

Habs mal eben schnell kurz zusammengetippt, aber nicht getestet. Ich hoffe aber mal, das da keine Fehler drin sind.

Moderiert von user profile iconTino: Code- durch Delphi-Tags ersetzt.