在Delphi XE2中TTable和TDBGrid的意外行为 [英] Unexpected behaviour of TTable and TDBGrid in Delphi XE2

查看:208
本文介绍了在Delphi XE2中TTable和TDBGrid的意外行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在表单上有一个文本框和一个网格。

I have a textbox and a grid on a form.

功能:当我在文本框中输入Emp ID(例如1,2,3等)时,对应于该Emp ID,应该从数据库进入Grid。当我再次输入另一个Emp ID时,另一个Emp名称应该嵌入在下一行的网格中,依此类推。的emp名字应该继续以这种方式进入网格的下一行。

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.

我的方法

我使用TTable,TDatasource和TDBGrid。当我在文本框中输入任何Emp ID并按Enter键时,我检查数据库中的Emp名称,然后将该名称附加到TTable。然后我将这个TTable分配给TDatasource,最后将TDatasource分配给TDBGrid。以下是此

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;

我的问题:我的问题是,表现异常。记录不按正确的顺序显示,而是彼此混合。表示网格中的数据行不显示在我用来追加的序列中。可能是什么问题呢。有我刷新一些数据源或dbgrid之前绑定每次或别的东西。请在此帮助。

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.

推荐答案

要定义记录的顺序,您必须使用索引/主键。
添加它如下面的代码。

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;

您可以通过定义DBGrid.Columns属性来隐藏EmpId以在网格中查看,其中只显示必要的列。

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

这篇关于在Delphi XE2中TTable和TDBGrid的意外行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆