0

I have a textbox and a grid on a form.

Functionality: When I enter an Emp ID (say 1, 2, 3 etc) in textbox, corresponding to that Emp ID, Emp Name should come in the Grid from database. When I again enter another Emp ID, Another Emp Name should get embedded in grid in next row and so on...as many times as I wish and no. of emp name should continue to come on next line of the grid in this way.

I think I have explained my question as I could.

My Approach

I am using TTable, TDatasource and TDBGrid for this. When I enter any Emp ID in textbox and press Enter, I check for Emp Name in database and then append that name to TTable. Then I assign this TTable to TDatasource and finally TDatasource to TDBGrid. Following is the code for this

Table1.Close;

//Create table for the first time

if not Table1.Exists  then
begin
      Table1.Close;

      Table1.DatabaseName    := 'databaseName';
      Table1.TableType           := ttParadox;
      Table1.TableName          := 'MyTable';
      Table1.FieldDefs.Clear;
      Table1.FieldDefs.Add('EmpName',ftString,40);
      Table1.CreateTable;

      Table1.Open;
end;

   Table1.Open;
   Table1.Append;
   Table1.FieldByName('EmpName').AsString := EmpName; //EmpName is fetched from database
   Table1.Post;
//Now assign this table to datasource
       DataSource1.DataSet := Table1;
//Now assign this datasource to dbgrid
       DBGrid1.DataSource := DataSource1;

My Problem: My problem is that, the records shown in the grids are behaving abnormally. Records are not shown in proper sequence but intermixed with each other. Means data rows in the grid are not show in the sequence which I used to append. What could be the problem. Has I to refresh some datasource or dbgrid before binding everytime or something else. Please help in this.

LU RD
  • 34,438
  • 5
  • 88
  • 296

1 Answers1

0

To define the order of records you have to use indexes/primary key. Add it like in code below.

Table1.FieldDefs.Add('EmpId', ftAutoInc, 0, True);
Table1.FieldDefs.Add('EmpName', ftString, 40);
Table1.IndexDefs.Add('idxEmpId','EmpId',[ixPrimary]);
Table1.CreateTable;
Table1.Open;

You can hide EmpId from viewing in grid by defining DBGrid.Columns property, where show only necessary columns.