Recent

Author Topic: How to copy to a DBGrid from a StringGrid or StringList?  (Read 10324 times)

IPguy

  • Sr. Member
  • ****
  • Posts: 385
How to copy to a DBGrid from a StringGrid or StringList?
« on: January 09, 2012, 03:29:53 am »
(Not sure if this question belongs in General, Networking or Databases ...)

I'm converting an app which uses tStringGrids and tStringLists to using tDBGrids.

I'm doing a SNMPWalk, which returns the data into a tStringList.  I'm currently copying the lines into a tStringGrid and want to change the destination to a tDBGrid.

1) Is there an easy way to copy / transfer the contents of a tStringList to a tDBGird?
Based on my research, it appears that I have to loop through the rows of the tStringList and do a copy from the tStringList to the DBGrid using SQLQuery1.AppendRecord(). 

2) Same question for a tStringGrid to a tDBGrid?

Eko Wahyudin

  • New Member
  • *
  • Posts: 21
  • Indonesia
Re: How to copy to a DBGrid from a StringGrid or StringList?
« Reply #1 on: January 09, 2012, 07:53:05 am »
receive data from StringGrid and insert to DBGrid.DataSource.DataSet.

I Made a simple procedure here... but still rough, hope you correct this code by your self.
Code: [Select]
procedure CopyStringGridToDBGrid(AStrGrid: TStringGrid; ADbGrid: TDbGrid);
var
  LFieldName: String;
  I,II, J,JJ: Integer;
  DS: TDataSet;
begin
  JJ:= AStringGrid.RowCount;
  J:= AStringGrid.ColCount ;
  DS:= ADbGrid.DataSource.DataSet;

  try
    for II:= 1 to JJ do begin  //Row loop
      DS.Insert;
      for I:= 1 to J do begin  //Cols loop
        LFieldName:= ADbGrid.Cells[I, 0];
        DS.FieldByName(LFieldName).AsString := Cells[I, II];
      end;
      DS.Post;
    end;
  except
     on E:Exception do begin
       //do your exception here
     end;
  end;
end;

note: This code is not tested yet!

IPguy

  • Sr. Member
  • ****
  • Posts: 385
Re: How to copy to a DBGrid from a StringGrid or StringList?
« Reply #2 on: January 09, 2012, 01:42:04 pm »
Thanks Eko.
I'm likely to replace your inner loop with an AppendRecord([]), as my StringGrid and DBGrid are not identical.

How would you deal with adding record index values?

Eko Wahyudin

  • New Member
  • *
  • Posts: 21
  • Indonesia
Re: How to copy to a DBGrid from a StringGrid or StringList?
« Reply #3 on: January 09, 2012, 04:07:18 pm »
Well, if you sure about the field sequence. You can change the column loop with AppendRecord([]) as you like :).

my code already field sequence less. But the field name must be precisely same.
« Last Edit: January 09, 2012, 04:12:40 pm by Eko Wahyudin »

 

TinyPortal © 2005-2018