此代碼使用分隔符獲取每行的 StringGrid 內容'|'。
procedure TForm1.datas();
var
iRow: integer;
RowData : string;
begin
{get stringgrid content}
for iRow := 1 to Form7.StringGrid1.RowCount -1 do // count rows
begin
RowData := Form7.StringGrid1.Cells[0, iRow] '|' Form7.StringGrid1.Cells[1, iRow] '|' Form7.StringGrid1.Cells[2, iRow] '|' Form7.StringGrid1.Cells[3, iRow] '|' Form7.StringGrid1.Cells[4, iRow] '|' Form7.StringGrid1.Cells[5, iRow] '|';
names := RowData; // it only get the last row in string grid :(
end;
end;
此代碼用于將資料保存到資料庫:
{SAVE}
procedure TForm1.SaveBtnClick(Sender: TObject);
begin
datas; // get data
with SQLQuery4 do
begin
if RecordCount = 0 then
begin
close;
SQL.Text := 'Insert into my_db(names) values(:names)';
Params.ParamByName('names').AsString := names;
ExecSQL;
SQLTransaction4.Commit;
Close;
ShowMessage('Records Successfully Saved!');
end;
end;
end;
我想將所有 StringGrid 行保存到一個資料庫列中,但它只保存最后一行的資料:(
我想把它保存在我的資料庫列中:
A|B|C|D|E| // first row
F|G|H|I|J| // second row
uj5u.com熱心網友回復:
在您的datas()方法內部,每次回圈迭代都僅用當前行的資料覆寫的值。names這就是為什么您只保存分配給的最后一行names。您需要改為將每一行附加names到,保留其現有資料,例如:
procedure TForm1.datas();
var
iRow: integer;
RowData : string;
begin
names := ''; // <-- RESET THE STRING HERE
{get stringgrid content}
for iRow := 1 to Form7.StringGrid1.RowCount -1 do // count rows
begin
RowData := Form7.StringGrid1.Cells[0, iRow] '|' Form7.StringGrid1.Cells[1, iRow] '|' Form7.StringGrid1.Cells[2, iRow] '|' Form7.StringGrid1.Cells[3, iRow] '|' Form7.StringGrid1.Cells[4, iRow] '|' Form7.StringGrid1.Cells[5, iRow] '|' sLineBreak;
names := names RowData; // <-- APPEND, NOT OVERWRITE!
end;
end;
不過,我可能會將其重寫為更像這樣的內容以對其進行清理:
procedure TForm1.datas();
var
iRow, iCol: integer;
Grid: TStringGrid;
begin
names := '';
{get stringgrid content}
Grid := Form7.StringGrid1;
for iRow := Grid.FixedRows to Grid.RowCount-1 do // count rows
begin
for iCol := Grid.FixedCols to Grid.ColCount-1 do // count colums
begin
names := names Grid.Cells[iCol, iRow] '|';
end;
names := names sLineBreak;
end;
end;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/460920.html
