如何动态增加一个Lookup字段 ( 积分: 100 )

F

flysand

Unregistered / Unconfirmed
GUEST, unregistred user!
procedure TForm1.OpenData;
var
AField:TStringField;
begin
dept.open;
with clientdataset1 do begin
open;
AField:=TStringfield.create(clientdataset1);
with AField do begin
Name:='dept';
Size:=30;
FieldKind := fkLookup;
LookupDataSet := dept;
LookupKeyFields := 'id';
LookupResultField := 'name';
KeyFields := 'deptid';
Lookup := True;
end;
Fields.Add(AField);

application.MessageBox(pchar(Fieldbyname('dept').AsString),'dd');//出错:字段dept没被发现
end;

end;

注,在dept表中的ID字段与clientdateset1表中的deptid字段同一类型,长度
 
procedure TForm1.OpenData;
var
AField:TStringField;
begin
dept.open;
with clientdataset1 do begin
open;
AField:=TStringfield.create(clientdataset1);
with AField do begin
Name:='dept';
Size:=30;
FieldKind := fkLookup;
LookupDataSet := dept;
LookupKeyFields := 'id';
LookupResultField := 'name';
KeyFields := 'deptid';
Lookup := True;
end;
Fields.Add(AField);

application.MessageBox(pchar(Fieldbyname('dept').AsString),'dd');//出错:字段dept没被发现
end;

end;

注,在dept表中的ID字段与clientdateset1表中的deptid字段同一类型,长度
 
这样比较麻烦啊,可以换一种思路,就是先建立好这个lookup字段,然后把它的visible属性设置成false,到你想让他出现的时候再让他的visible为true,这样和你动态增加的效果是相同的,还不是很麻烦。
 
好,帮顶


--------签名档---------------------------

比肩国内顶尖源码下载站点 -> 源码我爱你

http://www.source520.com
http://www.source520.net

80G源码电子书免费免注册下载,大量精辟技术文档库随时更新
 
好,帮顶


--------签名档---------------------------

比肩国内顶尖源码下载站点 -> 源码我爱你

http://www.source520.com
http://www.source520.net

80G源码电子书免费免注册下载,大量精辟技术文档库随时更新
 
你不是建立在 clientdataset1 么,怎么去显示 gz
 
哦,那一句写错,应改为:(原贴已改)
application.MessageBox(pchar(Fieldbyname('dept').AsString),'dd');//出错:字段dept没被发现
 
给字段命名用FieldName而不是Name,Name只是这个字段对象的名字,不是在数据集中的字段名
加上:FieldName:='dept';

你在设计期手工增加Lookup字段的时候就会看到,FieldName和Name的区别,FieldName就是字段名,而Name是字段对象名一般是ClientDataSet1Dept,即“数据集名+字段名”

动态建立字段的时候,数据集是不能打开的,建好之后才能打开。

在数据量大的时候,不宜建过多Lookup字段,实在不行可以是根据情况动态建立
 
to plenilune168:
把Name:='dept' 改为 FieldName:='dept'
结果一样出错!
 
再加上 SetFieldType 和 DataSet 的设置,这样应该可以的,我平常都是这样用的,结题给分吧

with clientdataset1 do
begin
open;
AField:=TStringfield.create(clientdataset1);
with AField do begin
FieldName:='dept';
Size:=30;
SetFieldType(ftString); //New
FieldKind := fkLookup;
DataSet:=clientdataset1; //New

Lookup := True;
LookupDataSet := dept;
KeyFields := 'deptid';
LookupKeyFields := 'id';
LookupResultField := 'name';
end;
Fields.Add(AField);
end;
 
DataSet:=clientdataset1; //error:can not perform this operation on an open dataset

还是不行啊!
 
先close 再open
 
cloes后前增加也不行: KeyFields := 'deptid';//error:field没被发现!

忘了说了,clientdataset1在设计时是没加任何字段的,在open后才由系统自动加入fields.
 
那肯定不行了,不能用动态的,设计器双击数据集把所有字符段加到clientdataset1中去

建立或者删除字段必需是数据集关闭的时候才行
 
顶部