如何只保留dbgrid中满足要求的数据,而且改变颜色(50分)

  • 主题发起人 主题发起人 skyline00
  • 开始时间 开始时间
S

skyline00

Unregistered / Unconfirmed
GUEST, unregistred user!
如何只保留dbgrid中满足要求的数据,而且改变颜色,比如'按照日期2006-07-31查询,在dbgrid中只显示该日期下数据,且改变颜色,假如有的列不用同时删除
 
修改连接DBGrid的连接组件的SQL语句或Filter 然后重画DBGrid
 
关于DBGRID的颜色改变:
在Delphi中随意控制DBGrid 每一行的颜色
中国地质大学研究生院
张兵兵 黄孝林
---- 有个问题是在Delphi中使用DBGrid时,如何让DBGrid中每一行颜色按照用户
自己的意愿控制。最初看到这个问题时,我们以为非常非常简单,所以马上动手准
备解决它。结果却发现不是那么回事,传统方法根本不能发挥作用。在电脑面前一
直坐到凌晨4点,不断地调试,幸运地是凭借平时积累的一点编程经验,终于找到了
开门的匙钥。现将它充公,供大家享用。

---- 1、 数据表的建立

---- 在Delphi的工具菜单中选择Database desktop,在数据库DBDemos下建立一
个名为example.db的数据表。数据表的字段和内容如下:


Name Age Wage
张山 25 500
王武 57 1060
李市 30 520
刘牛 28 390
 

---- 2、创建基于TDBGrid的TColoredDBGrid组件

---- 在Delphi组件菜单中,选择New Component,在弹出对话框中作以下设置:

Ancestor Type = TDBGrid
Class Name = TColoredDBGrid
 

---- 然后单击OK按钮,Delphi自动完成组件基本框架的定义。增添
OnDRawColoredDBGrid事件并使它出现在Object Inspector的Events中以便在应
用程序中设定改变行颜色的条件。重载DrawCell方法,只能自己绘制单元格。不能
通过在OnDrawColumnCell来设置颜色,因为在OnDrawColumnCell改变单元格的颜
色会再次触发OnDrawColumnCell。

---- 下面就是所创建组件的源程序 。

---- 3、建立应用程序进行验证。

---- 在Delphi文件菜单中选择New建立新的应用程序工程Project1和主窗体
Form1,设置Form1的Caption属性为“控制DBGrid行颜色的示例”。在主窗体
上添加Data Source、Table、Button和ColoredDBGrid组件。设置各组件的
属性如下:

Table1.Database=’DBDemos’
Table1.Tablename=’example.db’
Datasource1.Dataset=Table1
ColoredDBGrid1.Datasource=DataSource1
Button1.Caption=’退出’
 

---- 在ColoredDBGrid1的onDRawColoredDBGrid事件中输入下列代码,设定
由Wage(工资)来决定在ColoredDBGrid1各行的颜色。

procedure TForm1.ColoredDBGrid1 DRawColoredDBGrid
(Sender: TObject; Field: TField; var Color:
TColor; var Font: TFont);
Var
p : Integer;
begin
p := Table1.FindField('wage').AsInteger;
//取得当前记录的Wage字段的值。
if(p < 500) then begin
//程序将根据wage值设置各行的颜色。
Color := clGreen;
Font.Style := [fsItalic];
//不仅可以改变颜色,还可以改变字体
end;
if(p >= 500) And (p < 800) then
Color := clRed;
if(p >=800) then begin
Color := clMaroon;
Font.Style := [fsBold];
end;
end;
//用‘退出’按钮结束程序运行。
procedure TForm1.Button1Click(Sender: TObject);
begin
Close;
end;
 

---- 4、程序运行结果

---- 本程序在win98(中文版)和delphi4.0(C/S版)中测试运行,得到预计
的结果:第一行和第三行变为红色,第二行变为棕色,第四行为绿色,满足了基本要求。
 
在DBGrid中的DrawColumnCell事件中写:
if DataMod.QryContent.RecordCount>0 then
begin
if DataMod.QryContent.FieldByName('ISPASSED').AsInteger=0 then
(Sender as TDBGrid).Canvas.Brush.Color:=clMoneyGreen;
(Sender as TDBGrid).DefaultDrawColumnCell(Rect,DataCol,Column,State);
end;
改变颜色。
 
多人接受答案了。
 
后退
顶部