全國最多中醫師線上諮詢網站-台灣中醫網
發文 回覆 瀏覽次數:24817
推到 Plurk!
推到 Facebook!

DBGrid 應用全書

 
wwwbbs
初階會員


發表:41
回覆:59
積分:25
註冊:2003-05-23

發送簡訊給我
#1 引用回覆 回覆 發表時間:2007-12-19 03:14:00 IP:220.229.xxx.xxx 訂閱
在網路爬文時發現的,跟大家分享,如有侵犯著作請版主刪除。

0 then
ShowMessage('Vertical scrollbar is visible!');
if (GetWindowlong(Stringgrid1.Handle, GWL_STYLE) and WS_HSCROLL) <> 0 then
ShowMessage('Horizontal scrollbar is visible!');
。。。

2003-11-17 15:04:27 兩個Grid的同步滾動 在實際製作一個項目當中,有時候需要幾個grid一起同步滾動以減少用戶的操作量。希望下面那段代碼對您有一定的參考價值。
{1.}
unit SyncStringGrid;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,Dialogs, Grids;
type
TSyncKind = (skBoth, skVScroll, skHScroll);
TSyncStringGrid = class(TStringGrid)
private
FInSync: Boolean;
FsyncGrid: TSyncStringGrid;
FSyncKind: TSyncKind;
{ Private declarations }
procedure WMVScroll(var Msg: TMessage); message WM_VSCROLL;
procedure WMHScroll(var Msg: TMessage); message WM_HSCROLL;
protected
{ Protected declarations }
public
{ Public declarations }
procedure DoSync(Msg, wParam: Integer; lParam: Longint); virtual;
published
{ Published declarations }
property SyncGrid: TSyncStringGrid read FSyncGrid write FSyncGrid;
property SyncKind: TSyncKind read FSyncKind write FSyncKind default skBoth;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Samples', [TSyncStringGrid]);
end;
procedure TSyncStringGrid.WMVScroll(var Msg: TMessage);
begin
if not FInSync and Assigned(FSyncGrid) and (FSyncKind in [skBoth, skVScroll]) then
FSyncGrid.DoSync(WM_VSCROLL, Msg.wParam, Msg.lParam);
inherited;
end;
procedure TSyncStringGrid.WMHScroll(var Msg: TMessage);
begin
if not FInSync and Assigned(FSyncGrid) and (FSyncKind in [skBoth, skHScroll]) then
FSyncGrid.DoSync(WM_HSCROLL, Msg.wParam, Msg.lParam);
inherited;
end;
procedure TSyncStringGrid.DoSync(Msg, wParam: Integer; lParam: Longint);
begin
FInSync := True;
Perform(Msg, wParam, lParam);
FinSync := False;
end;
end.
{****************************************}
{2.}
private
OldGridProc1, OldGridProc2: TWndMethod;
procedure Grid1WindowProc(var Message: TMessage);
procedure Grid2WindowProc(var Message: TMessage);
public
{...}
procedure TForm1.Grid1WindowProc(var Message: TMessage);
begin
OldGridProc1(Message);
if ((Message.Msg = WM_VSCROLL) or (Message.Msg = WM_HSCROLL) or Message.msg = WM_Mousewheel)) then
begin
OldGridProc2(Message);
end;
end;
procedure TForm1.Grid2WindowProc(var Message: TMessage);
begin
OldGridProc2(Message);
if ((Message.Msg = WM_VSCROLL) or (Message.Msg = WM_HSCROLL) or (Message.msg = WM_Mousewheel)) then
begin
OldGridProc1(Message);
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
OldGridProc1 := StringGrid1.WindowProc;
OldGridProc2 := StringGrid2.WindowProc;
StringGrid1.WindowProc := Grid1WindowProc;
StringGrid2.WindowProc := Grid2WindowProc;
end;


2003-11-19 9:35:04 在Delphi中隨意控制DBGrid 每一行的顏色簡易方法 Delphi中使用 DBGrid 控件時,每一列都能按需要隨意地改變顏色,但要改變每一行的顏色卻很難,那麼在不重新製作新控制件的情況下,有沒有好的辦法讓DBGrid按照用戶自己要求隨意改變每一行顏色的?答案是有,下面介紹一種簡單的方法。
要改變DBGrid每一行的顏色,只要在ONDrawColumnCell事件中設定要改變顏色的行的條件,
並指定DBGrid的Canvas.Brush.color屬性並且把Canvas.pen.mode屬性設成pmmask,再調用DBGrid 的DefaultDrawColumnCell方法即可。注意在改變這兩個屬性前要先保護好原來的
Canvas.Brush.color 屬性的值,調節器用完成 DefaultDrawColumnCell 方法後要把原屬性值改
回,現以 Delphi\demos\db\clientmd 目錄下的演示程序 clintproj.dpr 為例子,做簡單說明,下面是對程序中的柵格 MemberGrid 的合條件的整行進行變色,變成黑體背景黃色的,其它不合條件的行的顏色為正常字體,白色背景,只在 DrawColumnCelL 事件中設條件其它的不變,如下:
procedure TClientForm.MemberGridDrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
var
oldcolor:tcolor;
oldpm:tpenmode;
begin
if DM.ProjectTEAM_LEADER.Value = DM.Emp_ProjEMP_NO.Value then {设定变色的行的条件}
MemberGrid.Canvas.Font.Style := [fsBold];
MemberGrid.DefaultDrawColumnCell(Rect, DataCol, Column, State);
{上面是演示程序的原内容,以下是增加部分}
if DM.ProjectTEAM_LEADER.Value =DM.Emp_ProjEMP_NO.Value then {设定变色的行的条件}
begin
oldpm:= MemberGrid.Canvas.pen.mode;
oldcolor:= MemberGrid.Canvas.Brush.color;
MemberGrid.Canvas.Brush.color:=clyellow;
MemberGrid.Canvas.pen.mode:=pmmask;
MemberGrid.DefaultDrawColumnCell(Rect, DataCol, Column, State);
MemberGrid.Canvas.Brush.color:=oldcolor;
MemberGrid.Canvas.pen.mode:=oldpm;
end;

end;

感覺上這個方法和前面的幾個顏色控制方法的原理是一樣的,都是通過ONDrawColumnCell事件來實現變色醒目美化的功能。:)

2003-11-19 9:43:56 如何在DBGrid中能支持多項記錄的選擇 這份文檔來自國外,粗略看了一下,很有用,推薦給大家學習使用。
【Question】: How to do multi-selecting records in TDBGrid?
When you add [dgMultiSelect] to the Options property of a DBGrid, you give yourself the ability to select multiple records within the grid.
The records you select are represented as bookmarks and are stored in the SelectedRows property.
The SelectedRows property is an object of type TBookmarkList. The properties and methods are described below.
// property SelectedRows: TBookmarkList read FBookmarks;
// TBookmarkList = class
// public
{* The Clear method will free all the selected records within the DBGrid *}
// procedure Clear;
{* The Delete method will delete all the selected rows from the dataset *}
// procedure Delete;
{* The Find method determines whether a bookmark is in the selected list. *}
// function Find(const Item: TBookmarkStr;
// var Index: Integer): Boolean;
{* The IndexOf method returns the index of the bookmark within the Items property. *}
// function IndexOf(const Item: TBookmarkStr): Integer;
{* The Refresh method returns a boolean value to notify whether any orphans were dropped (deleted) during the time the record has been selected in the grid. The refresh method can be used to update the selected list to minimize the possibility of accessing a deleted record. *}
// function Refresh: Boolean; True = orphans found
{* The Count property returns the number of currently selected items in the DBGrid *}
// property Count: Integer read GetCount;
{* The CurrentRowSelected property returns a boolean value and determines whether the current row is selected or not. *}
// property CurrentRowSelected: Boolean
// read GetCurrentRowSelected
// write SetCurrentRowSelected;
{* The Items property is a TStringList of TBookmarkStr *}
// property Items[Index: Integer]: TBookmarkStr
// read GetItem; default;
// end;
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Grids, DBGrids, DB, DBTables;
type
TForm1 = class(TForm)
Table1: TTable;
DBGrid1: TDBGrid;
Count: TButton;
Selected: TButton;
Clear: TButton;
Delete: TButton;
Select: TButton;
GetBookMark: TButton;
Find: TButton;
FreeBookmark: TButton;
DataSource1: TDataSource;
procedure CountClick(Sender: TObject);
procedure SelectedClick(Sender: TObject);
procedure ClearClick(Sender: TObject);
procedure DeleteClick(Sender: TObject);
procedure SelectClick(Sender: TObject);
procedure GetBookMarkClick(Sender: TObject);
procedure FindClick(Sender: TObject);
procedure FreeBookmarkClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
Bookmark1: TBookmark;
z: Integer;
implementation
{$R *.DFM}
file://Example of the Count property
procedure TForm1.CountClick(Sender: TObject);
begin
if DBgrid1.SelectedRows.Count > 0 then
begin
showmessage(inttostr(DBgrid1.SelectedRows.Count));
end;
end;
file://Example of the CurrentRowSelected property
procedure TForm1.SelectedClick(Sender: TObject);
begin
if DBgrid1.SelectedRows.CurrentRowSelected then
showmessage('Selected');
end;
file://Example of the Clear Method
procedure TForm1.ClearClick(Sender: TObject);
begin
dbgrid1.SelectedRows.Clear;
end;
file://Example of the Delete Method
procedure TForm1.DeleteClick(Sender: TObject);
begin
DBgrid1.SelectedRows.Delete;
end;
{*
This example iterates through the selected rows of the grid and displays the second field of the dataset.
The Method DisableControls is used so that the DBGrid will not update when the dataset is changed. The last position of the dataset is saved as a TBookmark.
The IndexOf method is called to check whether or not the bookmark is still existent.
The decision of using the IndexOf method rather than the Refresh method should be determined by the specific application.
*}
procedure TForm1.SelectClick(Sender: TObject);
var
x: word;
TempBookmark: TBookMark;
begin
DBGrid1.Datasource.Dataset.DisableControls;
with DBgrid1.SelectedRows do
if Count > 0 then
begin
TempBookmark:= DBGrid1.Datasource.Dataset.GetBookmark;
for x:= 0 to Count - 1 do
begin
if IndexOf(Items[x]) > -1 then
begin
DBGrid1.Datasource.Dataset.Bookmark:= Items[x];
showmessage(DBGrid1.Datasource.Dataset.Fields[1].AsString);
end;
end;
end;
DBGrid1.Datasource.Dataset.GotoBookmark(TempBookmark);
DBGrid1.Datasource.Dataset.FreeBookmark(TempBookmark);
DBGrid1.Datasource.Dataset.EnableControls;
end;
{*
This example allows you to set a bookmark and and then search for the bookmarked record within selected a record(s) within the DBGrid.
*}
file://Sets a bookmark
procedure TForm1.GetBookMarkClick(Sender: TObject);
begin
Bookmark1:= DBGrid1.Datasource.Dataset.GetBookmark;
end;
file://Frees the bookmark
procedure TForm1.FreeBookmarkClick(Sender: TObject);
begin
if assigned(Bookmark1) then
begin
DBGrid1.Datasource.Dataset.FreeBookmark(Bookmark1);
Bookmark1:= nil;
end;
end;
file://Uses the Find method to locate the position of the bookmarked record within the selected list in the DBGrid
procedure TForm1.FindClick(Sender: TObject);
begin
if assigned(Bookmark1) then
begin
if DBGrid1.SelectedRows.Find(TBookMarkStr(Bookmark1),z) then
showmessage(inttostr(z));
end;
end;
end.

2003-11-19 10:11:21 另外一種可以在在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;
file://取得當前記錄的Wage字段的值。
if (p < 500) then begin
file://程序將根據wage值設置各行的顏色。
Color := clGreen;
Font.Style := [fsItalic];
file://不僅可以改變顏色,還可以改變字體
end;
if(p >= 500) And (p < 800) then
Color := clRed;
if(p >=800) then begin
Color := clMaroon;
Font.Style := [fsBold];
end;
end;
file://用『退出』按鈕結束程序運行。
procedure TForm1.Button1Click(Sender: TObject);
begin
Close;
end;

2003-11-19 10:16:11 在一個Dbgrid中顯示多數據庫 在數據庫編程中,不必要也不可能將應用程序操作的所有數據庫字段放入一個數據庫文件中。正確的數據庫結構應是:將數據庫字段放入多個數據庫文件,相關的數據庫都包含一個唯一
的關鍵字段,在多數據庫結構裡可以建立聯繫。
例如:要編製一個人事管理程序,為簡化演示程序,只建立兩個數據庫,每個數據庫都只建
立兩個字段。
個人簡介 jianjie.dbf,由人事處維護;工資情況 gongzi.dbf,由財務處維護。
1.數據庫的建立
進入DataBase Desktop,建立數據庫結構如下:

jianjie.dbf
編號 字段名:bianhao size:4 type:number
姓名 字段名:xingming size:10 type:character
gongzi.dbf
編號 字段名:bianhao size:4 type:number
工資 字段名:gongzi size:4 Dec 2 type:number
注意: 兩個數據庫的bianhao字段的size、type必須一致。實際上,兩數據庫文件可以分佈
在網絡的不同計算機上,為便於演示,分別存為〞c: \test\jianjie.dbf〞和 〞c:\test
\gongzi.dbf〞。
2.應用程序的編制
啟動Delphi, 新建一個工程,在窗體中加入Query控件Query1,databasename屬性設為c:
\test;
加入DataSource控件datasource1, DataSet屬性設為Query1; 加入DbGrid控件 dbgrid1,
DataSource屬性設為DataSource1,將Query1.sql屬性設為
SELECT DISTINCT A.bianhao,a.xingming, b.gongzi
FROM 〞jianjie.dbf〞 A, 〞gongzi.DBF〞 b
WHERE A.bianhao=b.bianhao
再將Query1.enabled屬性設為True, 不用編譯, DbGrid1就會顯示: bianhao,
xingming, gongzi三個字段。如果jianjie.dbf和gongzi.dbf中有記錄,則記錄會顯示出來。因
篇幅所限,此文只介紹了Dbgrid中顯示多個數據庫內容的一般方法,讀者可在此基礎上進行完
善,使該方法更好地適應您的需要。


2003-11-19 10:19:40 在 DBGrid 中如何讓回車變為光標右移動
在Form.OnKeyPress事件中寫如下代碼:
if Key = #13 then
if ActiveControl = DBGrid1 then begin
TDBGrid(ActiveControl).SelectedIndex := TDBGrid(ActiveControl).SelectedIndex 1;
Key := #0;
end;
有2點需要注意:
1.當光標達到DBGird最右列的時候,再按回車,光標還會停留在原地。
2.Key := #0

2003-11-19 10:25:07 從 DBGrid 中複製記錄procedure TForm1.DBGrid1DblClick(Sender: TObject);
var
x : integer ;
HadToOpen : boolean ;
begin
with Sender as TDBGrid do begin
HadToOpen := not tTarget.Active ;
if HadToOpen then
tTarget.Active := True ;
tTarget.Append ;
for x := 0 to FieldCount - 1 do
case Fields[x].DataType of
ftBoolean : tTarget.FieldByName(Fields[x].FieldName).AsBoolean := Fields[x].AsBoolean
ftString : tTarget.FieldByName(Fields[x].FieldName).AsString := Fields[x].AsString
ftFloat : tTarget.FieldByName(Fields[x].FieldName).AsFloat := Fields[x].AsFloat
ftInteger : tTarget.FieldByName(Fields[x].FieldName).AsInteger := Fields[x].AsInteger
ftDate : tTarget.FieldByName(Fields[x].FieldName).AsDateTime := Fields[x].AsDateTime ;
end ;
tTarget.Post ;
if HadToOpen then
tTarget.Active := False ;
end ;
end;

2003-11-19 10:27:58 使用 DBGrid 的復選項(請參考如何在DBGrid中能支持多項記錄的選擇)procedure TForm1.SelectClick(Sender: TObject);
var
x: word;
TempBookmark: TBookMark;
begin
DBGrid1.Datasource.Dataset.DisableControls;
with DBgrid1.SelectedRows do
if Count <> 0 then
begin
TempBookmark:= DBGrid1.Datasource.Dataset.GetBookmark;
for x:= 0 to Count - 1 do
begin
if IndexOf(Items[x]) > -1 then
begin
DBGrid1.Datasource.Dataset.Bookmark:= Items[x];
showmessage(DBGrid1.Datasource.Dataset.Fields[1].AsString);
end;
end;
end;
DBGrid1.Datasource.Dataset.GotoBookmark(TempBookmark);
DBGrid1.Datasource.Dataset.FreeBookmark(TempBookmark);
DBGrid1.Datasource.Dataset.EnableControls;
end;


2003-11-19 10:32:27 在DBGrid上Drag & Drop(拖放)我們在做程序中發現,如果能夠讓用戶將一個Edit的內容直接拖放到一個DBGrid裡,會顯得很方便,但在程序編製過程中發現,似乎拖放只能拖放到當前的記錄上,那假如要拖放到其他記錄又怎麼辦呢,總不能讓用戶先選擇記錄,然後再拖放吧。
後來,通過研究發現,當用鼠標點DBGrid時,DBGrid會自動將記錄指針移動到所點擊的記錄上,這就給了我一個思路,讓程序模擬在DBGrid上的一次點擊先讓光標移動到那條記錄上,然後就可以將拖放的數據寫入DBgrid裡面了。
通過事實證明這個思路是可行的。下面,我就告訴大家我的做法:
1) 首先在Form上放一個DBGrid,並它能夠顯示記錄,(這比較簡單,就不用多說了)
2) 在Form上放一個Edit
3) 修改Edit的屬性,把DragMode改為dmAutoMatic, 讓用戶能夠拖放
4) 在Dbgrid的DragOver事件中增加如下代碼: 讓它能夠接收 Drag & drop
procedure TForm1.DBGrid1DragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean);
begin
accept:=true;
end;
5) 在Dbgrid的DragDrop事件中增加如下代碼: 讓它能夠自動跳到光標所指定的記錄上
procedure TForm1.DBGrid1DragDrop(Sender, Source: TObject; X, Y: Integer);
begin
if Source<>Edit1 then exit;
with Sender as TDbGrid do begin
Perform(wm_LButtonDown,0,MakeLong(x,y));
PerForm(WM_LButtonUp, 0,MakeLong(x,y));
SelectedField.Dataset.edit;
SelectedField.AsString:=Edit1.text;
end;
end;
至此,我們就實現了想要的功能,其中PerForm是TControl的一個通用方法目的是繞過Windows本身的消息循環,而將消息直接發給要發的Control,其具體使用方法請參考Delphi的幫助。

2003-11-19 10:39:19 如何使DBGrid的指針不移動?
【問題】:我用DBGRID顯示TABLE中的內容,現在我要從頭到尾讀一遍TABLE裡的數據,用
Table1.First,Next來做會使DBGRID裡面的指針也跟著跑,怎麼才能使這時候DBGRID裡面的指針不
動呢?
【答案】:使用如下代碼即可:
with DataSet do
try
DisableControls;
Do_something;
finally
EnableControls;
end;

2003-11-19 10:42:14 如何動態更新DBGrid的顏色?(請同時參考「如何使DBGRID網格的顏色隨此格中的數據值的變化而變化?」) DBGrid控件是一個有許多用戶接口的顯示數據庫的控件,以下的程序告訴您如何根據顯示的內容改變字體的顯示顏色。例如,如果一個城市的人口大於200萬,我們就讓它顯示為藍色。使用的控件事件為DBGrid.OnDrawColumeCell.
procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect:TRect;DataCol:
Integer; Column: TColumn; State: TGridDrawState);
begin
if Table1.FieldByName('Population').AsInteger > 20000000 then
DBGrid1.Canvas.Font.Color := clBlue;
DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;
上面的例子是簡單的,但是你可以根據自己的需要擴充,例如字體也變化等,甚至你可以調用畫圓的函數在數字上畫上一個紅色的圓圈。

2003-11-19 10:45:14 使用DBGrid顯示日期 在使用 DBGRID 控件時顯示 DATATIME 時其年份是為2位的,但我們在步入2000年後需要顯示的日期是4位,如:1998、2001。在數據庫中該字段只有在2000年後才會顯示4位,怎麼辦呢? 下面我們就讓該字段在DBGRID控件中也顯示4位的日期格式: 雙擊 Table1 控件,就會出現 form1.table 窗體,擊右鍵,選 Add Fields...,選擇日期字段後按ok,窗體中就出現了數據庫的日期字段名,點日期的那個字段名,屬性框裡就出現了該字段的信息,裡面有一項 DispalyFormat,在該顯示格式裡輸入 yyyy.mm.dd ,那麼DBGRID控件就出現完整的日期了。

2003-11-19 10:48:37 在TDBGrid控件中實現拖放的另外一個思路(請同時參考在DBGrid上Drag & Drop(拖放)) 在本unit中,自定義TMyCustomDBGrid=class(TCustomDBGrid),再如下引用:
TMyCustomDBGrid(DBGrid1).MouseDown(...)

DBGrid1 as TMyCustomDBGrid).MouseDown(...)即可。

2003-11-19 10:56:11 在dbgrid表格中如何設置按回車鍵相當於單click?【例程】:
在窗體form1中放入table1,datasource1,dbgrid1,設好聯連關係,使 dbgrid1 中能正確顯示出table1的數據。然後:
procedure TForm1.DBGrid1KeyPress(Sender: TObject;
var Key: Char);
begin
with DBGrid1 do
if Key=#13 then
DBGrid1CellClick(Columns[SelectedIndex]);
end;
procedure TForm1.DBGrid1CellClick(Column: TColumn);
begin
with DBGrid1 do
showmessage(format('row=%d',[SelectedIndex]));
end;

2003-11-19 11:07:55 Delphi 的 DBGrid 中的下拉列表和查找字段編程方法 數據網格是非常流行的數據輸入和顯示形式,像大家熟悉的Excel、VFP 中的功能強大的BROWS 等,為廣大程序員樂於採用。在用 Delphi 開發數據庫應用系統時,利用數據網格DBGrid 輸入數據時,有些字段只允許某幾個固定的字符串,像檔案案卷的保管期限,只有「永久」、「長期」和「短期」三種,可否從一個下拉列表中進行選擇,從而方便輸入和避免輸入錯誤呢?還有一些字段,例如職工信息庫中的單位編號(在另外的單位庫中保存著單位的詳細信息),在輸入和顯示職工數據時,能否不對單位編號進行操作,而代之於更加直觀的單位庫中的單位名稱呢?答案是肯定的,Delphi 的數據網格控件 DBGrid,支持下拉列表和查找字段的編程,而且,編程的過程都是可視化的,不需要寫一行語句。
一、DBGrid 中的下拉列表
在 DBGrid 網格中實現下拉列表,設置好 DBGrid 中該字段的 PickList 字符串列表、初始的序號值 DropDownRows 即可。以職工信息庫中的籍貫字段(字符串類型)為例,具體設計步驟如下:
1、在窗體上放置Table1、DataSource1、DBGrid1、DBNavigator1 等控件對象,按下表設置各個對象的屬性:
---------------------------------------
對像 屬性 設定值
---------------------------------------
Table1 DataBase sy1
Table zgk.dbf file://職工信息庫
DataSource1 DataSet Table1
DbGrid1 DataSource DataSource1
DBNavigator1 DataSource Datasource1
-------------------------------------------
2、雙擊Table1, 在彈出的Form1.Table1 窗口中,用右鍵彈出快捷菜單,單擊Add Fields 菜單項;選擇所有的字段後,按OK 按鈕。
3、修改第2 步新增字段的 DisplayLabel 屬性。以 Table1ZGBH 字段為例,在 Object Inspector 窗口中選擇 Table1ZGBH, 修改屬性 DisplayLabel= 職工編號,其餘字段類似。
4、雙擊 DBGrid1, 在彈出的 Editing DBGrid1.Columns 窗口中,單擊 Add all Fields 按鈕,增加Table1 的所有字段。
5、在 Editing DBGrid1.Columns 窗口,選擇 jg 這一行,切換到 Object Inspector 窗口,修改它的 PickList.Strings 為「湖北枝江市(換行)北京市(換行)河南平頂山市(換行)浙江德清市」
6、在 Form1.Oncreate 事件中寫入語句:
Table1.Open;
7、F9 運行,用鼠標點擊某個記錄的籍貫字段,右邊即出現一個按鈕,點擊這個按鈕,可出現一個下拉列表,包含第5 步中輸入的四行字符串,可用鼠標進行選擇。當然也可以自行輸入一個並不屬下拉列表中的字符串。
二、DBGrid 中的查找字段
所謂查找字段 (LookUp Field),即 DBGrid 中的某個關鍵字段的數值來源於另外一個數據庫的相應字段。運用查找字段技術,不僅可以有效的避免輸入錯誤,而且 DBGrid 的顯示方式更為靈活,可以不顯示關鍵字段,而顯示源數據庫中相對應的另外一個字段的數據。
---- 例如,我們在 DBGrid 中顯示和編輯職工信息,包括職工編號、職工姓名、籍貫、所在單位編號,而單位編號來源於另一個數據庫表格——單位庫,稱「單位編號」為關鍵字段。如果我們直接顯示和編輯單位編號的話,將會面對1、2、3 等非常不直觀的數字,編輯時極易出錯。但是如果顯示和編輯的是單位庫中對應的單位名稱話,將非常直觀。這就是DBGrid 的所支持的查找字段帶來的好處。
實現DBGrid 的查找字段同樣不需要任何語句,具體設計步驟如下:
1、在窗體上放置 Table1、Table2、DataSource1、DBGrid1、DBNavigator1 等控件對象,按下表設置各個對象的屬性:
---------------------------------------
對像 屬性 設定值
---------------------------------------
Table1 DataBase sy1
Table zgk.dbf file://職工信息庫
Table2 DataBase sy1
Table dwk.dbf file://單位信息庫
DataSource1 DataSet Table1
DbGrid1 DataSource DataSource1
DBNavigator1 DataSource Datasource1
------------------------------------------
2、雙擊 Table1, 在彈出的 Form1.Table1 窗口中,用右鍵彈出快捷菜單,單擊 Add Fields 菜單項;選擇所有的字段後,按OK 按鈕。
3、修改第2 步新增字段的 DisplayLabel 屬性。以 Table1ZGBH 字段為例,在 Object Inspector 窗口中選擇 Table1ZGBH, 修改屬性 DisplayLabel= 職工編號,其餘字段類似。
4、設置 Table1DWBH.Visible=False。
5、在 Form1.Table1 窗口,用右鍵彈出快捷菜單,單擊 New Field 菜單項,新增一個查找字段DWMC,在彈出的窗口設置相應的屬性, 按 OK 按鈕確認;在 Object Inspector 窗口,設置 Table1DWMC.DisplayLabel= 單位名稱。
6、在 Form1.Oncreate 事件中寫入語句:
Table1.Open;
7、按 F9 運行,當光標移至某個記錄的單位名稱字段時,用鼠標點擊該字段,即出現一個下拉列表,點擊右邊的下箭頭,可在下拉列表中進行選擇。在這裡可以看出,下拉列表的內容來自於單位信息庫,並且不能輸入其他內容。
三、DBGrid 中的下拉列表和查找字段的區別
雖然 DBGrid 中的下拉列表和查找字段,都是以下拉列表的形式出現的,但兩者有很大的差別。
1、用 PickList 屬性設置的下拉列表,它的數據是手工輸入的,雖然也可以在程序中修改,但動態特性顯然不如直接由另外數據庫表格提取數據的查找字段。
ace33022
一般會員


發表:2
回覆:41
積分:23
註冊:2004-05-14

發送簡訊給我
#2 引用回覆 回覆 發表時間:2007-12-20 11:00:38 IP:59.125.xxx.xxx 訂閱
感謝,先收下了,再找時間瞧一瞧 
系統時間:2024-05-15 11:50:18
聯絡我們 | Delphi K.Top討論版
本站聲明
1. 本論壇為無營利行為之開放平台,所有文章都是由網友自行張貼,如牽涉到法律糾紛一切與本站無關。
2. 假如網友發表之內容涉及侵權,而損及您的利益,請立即通知版主刪除。
3. 請勿批評中華民國元首及政府或批評各政黨,是藍是綠本站無權干涉,但這裡不是政治性論壇!