Search code examples
delphirowsdbgrid

Delphi reaching a DBGrid's rows


So i have a TDBGrid, my purpose is searching DBGrid's Fieldname and comparing it with my Edit's Text property and if they are equal then,

i want to write the whole column which i've found the match, to a ListBox.

With a for loop with fieldcount, i can compare FieldName, though since there is no rows or rowcount property i can use, i don't know how i would get the index of this whole column.

for i:=0 to DBGrid1.FieldCount-1 do
begin
 if DBGrid1.Fields[i].FieldName=Edit1.Text then
   for j:=1 to DBGrid1.RowCount-1 do
     ListBox1.Items.Add(DBGrid1.Rows.Fields[i].Index.AsString);
end;

This is an imaginary code of what im trying to do...

P.S.:I'm still using Delphi 7, (educational reasons)


Solution

  • You can't get the row values directly from the DbGrid. Instead, you have to navigate through the dataset that's used to feed the DbGrid.

    This example assumes you are using a TClientDataSet.

    for i := 0 to DBGrid1.FieldCount - 1 do
    begin
      if DBGrid1.Fields[i].FieldName = Edit1.Text then
      begin
        ClientDataSet1.DisableControls;
        try
          ClientDataSet1.First();
          while (not ClientDataSet1.Eof) do
          begin
            ListBox1.Items.Add(ClientDataSet1.FieldByName(Edit1.Text).AsString);
            ClientDataSet1.Next();
          end;
        finally
          ClientDataSet1.EnableControls;
        end;
      end;
    end;