Главная страница
Top.Mail.Ru    Яндекс.Метрика
Текущий архив: 2005.02.27;
Скачать: CL | DM;

Вниз

Cохранить в файл содержимое TListView   Найти похожие ветки 

 
TBeginner ©   (2005-02-12 22:24) [0]

Здравствуйте!
Вот, столкнулся с проблемой: нужно сохранить в файл содержимое TListView, но как это сделать, знает кто-нить? Help me, please!


 
Eraser ©   (2005-02-12 22:40) [1]

Попробуй для этой цели исользовать Ini файл.


 
Kladbische   (2005-02-12 23:11) [2]

Слушай с listBox вот как

with ListBox1.Items do
begin
 savetofile(ExtractFilePath(Application.ExeName)
 + (Edit1.text+".txt"));
end;

Может поможет.


 
Alexander Panov ©   (2005-02-13 00:44) [3]

Пробежаться по строкам, динамически заполнить TStrinlist, разделив строки разделителями, сохранить в файл.
Заполнить TListView - обратная операция.


 
kaZaNoVa ©   (2005-02-13 05:17) [4]

Alexander Panov ©   (13.02.05 0:44) [3]
а что лучше, TStrings или TStringList ?


 
TBeginner ©   (2005-02-13 14:24) [5]

Kladbische, но мне нужно TListView...


 
Vit@ly ©   (2005-02-13 14:41) [6]

Нашел, но не тестировал :(

procedure TForm1.SaveListViewToFile(AListView: TListView; sFileName: string);
var
 idxItem, idxSub, IdxImage: Integer;
 F: TFileStream;
 pText: PChar;
 sText: string;
 W, ItemCount, SubCount: Word;
 MySignature: array[0..2] of Char;
begin
 //Initialization
 with AListView do
 begin
   ItemCount := 0;
   SubCount := 0;
   //****
   MySignature := "LVF";
   // ListViewFile
   F := TFileStream.Create(sFileName, fmCreate or fmOpenWrite);
   F.Write(MySignature, SizeOf(MySignature));
   if Items.Count = 0 then
     // List is empty
     ItemCount := 0
   else
     ItemCount := Items.Count;
   F.Write(ItemCount, SizeOf(ItemCount));
   if Items.Count > 0 then
   begin
     for idxItem := 1 to ItemCount do
     begin
       with Items[idxItem - 1] do
       begin
         //Save subitems count
         if SubItems.Count = 0 then
           SubCount := 0
         else
           SubCount := Subitems.Count;
         F.Write(SubCount, SizeOf(SubCount));
         //Save ImageIndex
         IdxImage := ImageIndex;
         F.Write(IdxImage, SizeOf(IdxImage));
         //Save Caption
         sText := Caption;
         w := Length(sText);
         pText := StrAlloc(Length(sText) + 1);
         StrPLCopy(pText, sText, Length(sText));
         F.Write(w, SizeOf(w));
         F.Write(pText^, w);
         StrDispose(pText);
         if SubCount > 0 then
         begin
           for idxSub := 0 to SubItems.Count - 1 do
           begin
             //Save Item"s subitems
             sText := SubItems[idxSub];
             w := Length(sText);
             pText := StrAlloc(Length(sText) + 1);
             StrPLCopy(pText, sText, Length(sText));
             F.Write(w, SizeOf(w));
             F.Write(pText^, w);
             StrDispose(pText);
           end;
         end;
       end;
     end;
   end;
   F.Free;
 end;
end;

procedure TForm1.LoadListViewToFile(AListView: TListView; sFileName: string);
var
 F: TFileStream;
 IdxItem, IdxSubItem, IdxImage: Integer;
 W, ItemCount, SubCount: Word;
 pText: PChar;
 PTemp: PChar;
 MySignature: array[0..2] of Char;
 sExeName: string;
begin
 with AListView do
 begin
   ItemCount := 0;
   SubCount := 0;
   sExeName := ExtractFileName(sFileName);
   if not FileExists(sFileName) then
   begin
     MessageBox(Handle, PChar(Format(Msg1, [sExeName])), "I/O Error",
       MB_ICONERROR);
     Exit;
   end;
   F := TFileStream.Create(sFileName, fmOpenRead);
   F.Read(MySignature, SizeOf(MySignature));
   if MySignature <> "LVF" then
   begin
     MessageBox(Handle, PChar(Format(Msg2, [sExeName])), "I/O Error",
       MB_ICONERROR);
     Exit;
   end;
   F.Read(ItemCount, SizeOf(ItemCount));
   Items.Clear;
   for idxItem := 1 to ItemCount do
   begin
     with Items.Add do
     begin
       //Read imageindex
       F.Read(SubCount, SizeOf(SubCount));
       //Read imageindex
       F.Read(IdxImage, SizeOf(IdxImage));
       ImageIndex := IdxImage;
       //Read the Caption
       F.Read(w, SizeOf(w));
       pText := StrAlloc(w + 1);
       pTemp := StrAlloc(w + 1);
       F.Read(pTemp^, W);
       StrLCopy(pText, pTemp, W);
       Caption := StrPas(pText);
       StrDispose(pTemp);
       StrDispose(pText);
       if SubCount > 0 then
       begin
         for idxSubItem := 1 to SubCount do
         begin
           F.Read(w, SizeOf(w));
           pText := StrAlloc(w + 1);
           pTemp := StrAlloc(w + 1);
           F.Read(pTemp^, W);
           StrLCopy(pText, pTemp, W);
           Items[idxItem - 1].SubItems.Add(StrPas(pText));
           StrDispose(pTemp);
           StrDispose(pText);
         end;
       end;
     end;
   end;
   F.Free;
 end;
end;

// Example:
procedure TForm1.Button1Click(Sender: TObject);
begin
 // Save Items and Clear the ListView
 SaveListViewToFile(ListView1, "MyListView.sav");
 ListView1.Items.Clear;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
 // Load Items
 LoadListViewToFile(ListView1, "MyListView.sav");
end;


 
Eraser ©   (2005-02-13 14:47) [7]

Vit@ly ©
Ну и накрутил...
Повторяю! Используй Ini файл, при этом названиям секций будет дан первичный индекс (т.е. поле в твоём листвью, которое уникально), итемы будут соответствовать колонкам твоеко ListView.
Можно так же и XML использовать... в любом случае будет проще и надёжнее чем в [6].


 
Ivolg ©   (2005-02-13 17:07) [8]

Нормально работает:

unit Unit1;

interface

uses
 Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
 Dialogs, StdCtrls, Buttons, ExtCtrls, jpeg, ComCtrls, ImgList;

type
 TForm1 = class(TForm)
   lv: TListView;
   procedure SaveToFile(Dir:string);
   function LoadFromFile(Dir:string):boolean;
 private
   { Private declarations }
 public
   { Public declarations }
 end;

var
 Form1: TForm1;
 it:TListItem;
 Signature,FileName:string;
implementation

{$R *.dfm}

procedure TForm1.SaveToFile(Dir:string);
var
 idxItem, idxSub, IdxImage: Integer;
 F: TFileStream;
 pText: PChar;
 sText: string;
 W, ItemCount, SubCount: Word;
 MySignature: array [0..7] of Char;
begin
 FileName:=dir;
 StrPCopy(MySignature, Signature);
 F := TFileStream.Create(FileName, fmCreate or fmOpenWrite);
 F.Write(MySignature, SizeOf(MySignature));
 ItemCount := lv.Items.Count;
 F.Write(ItemCount, SizeOf(ItemCount));
 if lv.Items.Count > 0 then
   for idxItem := 1 to ItemCount do
      with lv.Items[idxItem - 1] do
         begin
           SubCount := Subitems.Count;
           F.Write(SubCount, SizeOf(SubCount));
           IdxImage := ImageIndex;
           F.Write(IdxImage, SizeOf(IdxImage));
           sText := Caption;
           w := Length(sText);
           pText := StrAlloc(Length(sText) + 1);
           StrPLCopy(pText, sText, Length(sText));
           F.Write(w, SizeOf(w));
           F.Write(pText^, w);
           StrDispose(pText);
           if SubCount > 0 then
             for idxSub := 0 to SubItems.Count - 1 do
               begin
                 sText := SubItems[idxSub];
                 w := Length(sText);
                 pText := StrAlloc(Length(sText) + 1);
                 StrPLCopy(pText, sText, Length(sText));
                 F.Write(w, SizeOf(w));
                 F.Write(pText^, w);
                 StrDispose(pText);
               end;
         end;
 F.Free;
end;
function TForm1.LoadFromFile(Dir:string):boolean;
var
 F: TFileStream;
 IdxItem, IdxSubItem, IdxImage: Integer;
 W, ItemCount, SubCount: Word;
 pText: PChar;
 PTemp: PChar;
 MySignature: array [0..7] of Char;
begin
 FileName:=Dir;
 Result:=True;
 if not FileExists(FileName) then
   begin
     Result:=False;
     Exit;
   end;
 lv.Items.BeginUpdate;
 F := TFileStream.Create(FileName, fmOpenRead);
 F.Read(MySignature, SizeOf(MySignature));
 if MySignature <> Signature then
   begin
     F.Free;
     Result:=False;
     Exit;
   end;
 F.Read(ItemCount, SizeOf(ItemCount));
 lv.Items.Clear;
 for idxItem := 1 to ItemCount do
   with lv.Items.Add do
     begin
       F.Read(SubCount, SizeOf(SubCount));
       F.Read(IdxImage, SizeOf(IdxImage));
       ImageIndex := IdxImage;
       F.Read(w, SizeOf(w));
       pText := StrAlloc(w + 1);
       pTemp := StrAlloc(w + 1);
       F.Read(pTemp^, W);
       StrLCopy(pText, pTemp, W);
       Caption := StrPas(pText);
       StrDispose(pTemp);
       StrDispose(pText);
       if SubCount > 0 then
         for idxSubItem := 1 to SubCount do
           begin
             F.Read(w, SizeOf(w));
             pText := StrAlloc(w + 1);
             pTemp := StrAlloc(w + 1);
             F.Read(pTemp^, W);
             StrLCopy(pText, pTemp, W);
             lv.Items[idxItem - 1].SubItems.Add(StrPas(pText));
             StrDispose(pTemp);
             StrDispose(pText);
           end;
     end;
 F.Free;
 lv.Items.EndUpdate;
end;


 
begin...end ©   (2005-02-13 20:58) [9]

А у кого ещё длиннее? :-)


 
Плохиш ©   (2005-02-13 21:08) [10]


>kaZaNoVa ©   (13.02.05 05:17) [4]

>Alexander Panov ©   (13.02.05 0:44) [3]
>а что лучше, TStrings или TStringList ?

У тебя есть выбор? Загляни в справку.


 
Adder ©   (2005-02-13 21:28) [11]


> begin...end ©   (13.02.05 20:58) [9]
> А у кого ещё длиннее? :-)

У меня наверное -)


var
 Delimiter:Char=";";
.............
procedure TFormMain.SaveList1Click(Sender: TObject);
var i,j:integer;
   SL:TStringList;
   s:string;
begin
SaveDialog1.FileName:="File.txt";
if SaveDialog1.Execute then
begin
   SL:=TStringList.Create;
   s:="";
       ProgressBar1.Position:=0;
       ProgressBar1.Min:=0;
       ProgressBar1.Max:=ListView1.Items.Count;
try
   for i:=0 to ListView1.Columns.Count-1 do
       s:=s+ListView1.Columns[i].Caption+Delimiter;//";";
   SL.Add(s);
   for j:=0 to ListView1.Items.Count-1 do
   begin
   s:=ListView1.Items[j].Caption;
       for i:=0 to ListView1.Items[j].SubItems.Count-1 do
       begin
       s:=s+Delimiter+ListView1.Items[j].SubItems[i];
       end;
   SL.Add(s);
       ProgressBar1.Position:=ProgressBar1.Position+1;
       Application.ProcessMessages;
   end;
   SL.SaveToFile(SaveDialog1.FileName);
   finally
  SL.Free;
  end;
end;
end;


 
dimaxx ©   (2005-02-13 22:01) [12]

2 Vit@ly & Ivolg: Это выдержки кода компонента SmartListView, который поддерживает чтение/запись содержимого ListView. Код абсолютно рабочий - проверено. Сам пользовался.

2 TBeginner: Бери его за основу и не парься.



Страницы: 1 вся ветка

Текущий архив: 2005.02.27;
Скачать: CL | DM;

Наверх




Память: 0.51 MB
Время: 0.025 c
1-1108369082
Sash
2005-02-14 11:18
2005.02.27
как копировать файл?


14-1107470118
Usser
2005-02-04 01:35
2005.02.27
ZX-Spectrum (вспомнить молодость)


14-1107775727
Vasya.ru
2005-02-07 14:28
2005.02.27
А какие вообще разрешения экранов бывают?


14-1107530105
Pat
2005-02-04 18:15
2005.02.27
Колонтитулы в Excel е


1-1107949688
Polo
2005-02-09 14:48
2005.02.27
Печать через TRichEdit