2.Delphi5 - 隔行改变DBGrid网格颜色 :
在 Form1 上放置 DBGrid1、Query1、DataSource1 三个数据库组件,设置相关的属性,使 DBGrid1 能显示表中的数据。然后,在 DBGrid1 的 onDrawColumnCell 事件中键入以下代码,然后运行程序
procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
var i:integer;
begin
if gdSelected in State then Exit; //隔行改变网格背景色:
if adoQuery1.RecNo mod 2 = 0 then
(Sender as TDBGrid).Canvas.Brush.Color := clinfobk //定义背景颜色
else
(Sender as TDBGrid).Canvas.Brush.Color := RGB(191, 255, 223); //定义背景颜色
//定义网格线的颜色:
DBGrid1.DefaultDrawColumnCell(Rect,DataCol,Column,State);
with (Sender as TDBGrid).Canvas do //画 cell 的边框
begin
Pen.Color := $00ff0000; //定义画笔颜色(蓝色)
MoveTo(Rect.Left, Rect.Bottom); //画笔定位
LineTo(Rect.Right, Rect.Bottom); //画蓝色的横线
Pen.Color := clbtnface; //定义画笔颜色(兰色)
MoveTo(Rect.Right, Rect.Top); //画笔定位
LineTo(Rect.Right, Rect.Bottom); //画绿色
end;
end;
3. DBGrid指定列上显示DBComboBox
设置DBGrid1的OnDrawDataCell事件如下:
procedure TForm1.DBGrid1DrawDataCell(Sender: TObject; const Rect: TRect; Field: TField; State: TGridDrawState);
begin
if (gdFocused in State) then
begin
if (Field.FieldName = DBComboBox1.DataField ) then
begin
DBComboBox1.Left := Rect.Left + DBGrid1.Left;
DBComboBox1.Top := Rect.Top + DBGrid1.top;
DBComboBox1.Width := Rect.Right - Rect.Left;
DBComboBox1.Height := Rect.Bottom - Rect.Top;
DBComboBox1.Visible := True;
end;
end;
end;
2)、DBGrid指定单元格未获得焦点时不显示DBComboBox,设置DBGrid1的OnColExit事件如下:
procedure TForm1.DBGrid1ColExit(Sender: TObject);
begin
If DBGrid1.SelectedField.FieldName = DBComboBox1.DataField then
begin
DBComboBox1.Visible := false;
end;
end;
3)、当DBGrid指定列获得焦点时DrawDataCell事件只是绘制单元格,并显示DBComboBox,但是DBComboBox并没有获得焦点,数据的输入还是在单元格上进行。在DBGrid1的KeyPress事件中调用SendMessage这个 Windows API函数将数据输入传输到DBComboBox上,从而达到在DBComboBox上进行数据输入。因此还要设置KeyPress事件如下:
procedure TForm1.DBGrid1KeyPress(Sender: TObject; var Key: Char);
begin
if (key < > chr(9)) then
begin
if (DBGrid1.SelectedField.FieldName =DBComboBox1.DataField) then
begin
DBComboBox1.SetFocus;
SendMessage(DBComboBox1.Handle,WM_Char,word(Key),0);
end;
end;
end;
本文地址:http://com.8s8s.com/it/it4570.htm