I'm new here so feel free to give feedback on my way of asking.
For a project at school I need to open html files with tables in a stringgrid using Lazarus. My teacher said I need to use pos
to locate the html tags, and using <th>
and <tr>
I should be able to define the rows and columns, but I find it very difficult.
I'm not that far with this problem, I'm stuck at an early step. I'm trying to look if my pos
is working, but it doesn't really. My idea: clicking on Button1
will open OpenDialog1
. Then I choose a html file and my program will search for the text in Pos('<th', filename)
(see the included code). The position of that text will be put in Label1
.
I get this error:
unit1.pas(46,30) Error: Incompatible type for arg no. 2: Got "TStringList", expected "Variant"
So my subquestion is: How can I use pos
in a file?
This is the code I use. Feel free to ask and give feedback. Thanks in advance!
procedure HtmlToGrid(Grid: TStringGrid; const FileName: string; Sender: TObject);
var
TextFile, Line: TStringList;
Row: Integer;
Col: Integer;
prob: Integer;
begin
Grid.RowCount := 0; //clear any previous data
TextFile := TStringList.Create;
Textfile.LoadFromFile(filename);
prob := Pos('<th', TextFile);
if (Sender is TLabel) then
TLabel(Sender).Caption := IntToStr(prob);
end;
procedure TForm1.Button1Click(Sender: TObject);
var filename : string;
begin
if OpenDialog1.Execute then begin
filename:= OpenDialog1.FileName;
HtmlToGrid(database, filename, Label1);
end;
end;
The point that's causing you difficulty, I think, is not being aware that once you've loaded a file into a TStringList, the contents of the TStringList are accessible as a sstring via its Text property, so you can do something like
var
P : integer;
[...]
P := Pos('<th', Textfile.Text).
But possibly, you want to process the file line by line, which you can do using the TStringList's Strings property as in
S := MyStringList.Strings[Index].
Be aware that the Strings property is zero based, so the first list is MyStringLIst.Strings[0].
You could process your TextFile contents line-by-line like this
var
i : Integer;
[...]
for i := 0 to TextFile.Count - 1 do begin
if Pos('<th', TextFile.Strings[i]) > 0 then
{ do something }
end;
Btw, its best to give your variables a name which reflects their type, and 'TextFile' is a bit misleading for something that's actually a TStringList, so the name 'StringList' might be preferable to 'TextFile'.
It's well worth spending half an hour reading up on TStringList in the online help.