We help IT Professionals succeed at work.

Saving StringList to steam / load stream to string grid

meik goode
meik goode asked
on
implementation
My code below is producing the indicated exception any help in correcting the code would be appreciated.


Var ms: TMemoryStream;
      StrList: TStringList;

 StrList := TStringList.Create;
 StrList.Delimiter := '|';
 StrList.StrictDelimiter := True;

 StrList.Add('#|Path|File|.ext|Size|units');
 StrList.Add('1|c:\path|Filename|.bat|256|MB');
 
 ms := TMemoryStream.Create;
 If StrList.Count >= 1 Then StrList.SaveToStream(ms);

 ms.Position := 0;
 StringGrid.LoadFromStream(ms); //TMS StringGrid   <<= ERROR

{
---------------------------
Debugger Exception Notification
---------------------------
Project raised exception class EConvertError with message ''' is not a valid integer value'.
}

 ms.Free;
 StrList.Free
Comment
Watch Question

Commented:
You're trying to convert a string to an integer value using a bad string,  for example containing trailing blanks, a decimal point or invalid decimal characters.

Check your StrToInt(..) commands...
Top Expert 2011
Commented:
You should be using "LoadFromCSVStream" rather than "LoadFromStream":
var
  ms: TMemoryStream;
  StrList: TStringList;
begin
  StrList := TStringList.Create;

  {The following lines are not useful, and at this point are irrelevant, unless you are adding the text through DelimitedText:
  StrList.DelimitedText:= '#|Path|File|....';}
  //StrList.Delimiter := '|';
  //StrList.StrictDelimiter := True;

  StrList.Add('#|Path|File|.ext|Size|units');
  StrList.Add('1|c:\path|Filename|.bat|256|MB');

  ms := TMemoryStream.Create;
  If StrList.Count >= 1 Then StrList.SaveToStream(ms);

  ms.Position := 0;
  StringGrid1.LoadFromCSVStream(ms);

  ms.Free;
  StrList.Free;

Open in new window

Author

Commented:
each record in the stringlist (strlist) is being added to the stringlist as a string.  If the SaveToStream was parsing and storing numeric values from the string (which would then need to be reconverted back to a string value) I'm not sure how I would do this prior to the StringGrid "LoadFrom ..." and then to each stringgrid field.  I must say, though, I'm somewhat new to using Streams and don't understand their nuances.

I did miss seeing the "LoadFromCSVStream" stringgrid procedure option until jimyX pointed me to it.
With this procedure change the code executed without complaint.  I also appreciated the optimization suggestion by removing a few lines of code.

I'm very grateful for all suggestions and the time spent on my behalf
regard M.