在Delphi的DBGrid中插入其他可視元件

2021-08-27 01:56:30 字數 2675 閱讀 4387

---- delphi提供了功能強大的 dbgrid元件,以方便進行資料庫應用程式設計。但是如果我們僅僅利用dbgrid元件,每乙個獲得焦點(grid)只是乙個簡單的文字編輯框,不方便使用者輸入資料。delphi也提供了一些其他資料元件來方便使用者輸入,比如dbcombobox,dbcheckbox等元件,但這些元件卻沒有dbgrid功能強大。delphi能不能象visual foxpro那樣讓dbgrid中獲得焦點網格可以是其它可視資料元件以方便使用者呢?其實我們可以通過在dbgrid中插入其他可視元件來實現這一點。

---- delphi對dbgrid處理的內部機制,就是在網格上浮動乙個元件——dbedit元件。你輸入資料的網格其實是浮動dbedit元件,其他未獲得焦點地方不過是影象罷了。所以,在dbgrid中插入其他可視元件就是在網格上浮動乙個可視元件。因此任何元件,包括從簡單的dbcheckbox到複雜的對話方塊,都可以在dbgrid中插入。下面就是乙個如何在dbgrid中插入dbcombobox元件的步驟,採用同樣的辦法可以插入其他元件。

---- 1、 在delphi 中新建乙個專案。

---- 2、 分別拖動的data access元件板上datasource、table,data controls元件板上dbgrid,dbcombobox四個元件到form1上。

---- 3、 設定各個元件的屬性如下:

rcf1 物件 屬性 設定植

form1 caption '在dbgrid中插入spinedit元件示例'

datasource1 dataset table1

table1 databasename 'dbdemos'

tablename 'teacher.dbf'

active true

dbgrid1 datasource datasource1

dbcombobox1 datafield '***'

datasource datasource1

visible false

items.strings '男'| '女'

---- 注意:我在這裡用了teacher.dbf,那是反映教職工的性別,只能是「男」或者是「女」。

---- 4、 drawdatacell事件是繪製單元格,當獲得焦點網格所對應的字段與組合框所對應的字段一致時,移動組合框到獲得焦點的網格上,並且使組合框可視,從而達到在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;

---- 5、 dbgrid指定單元格未獲得焦點時不顯示dbcombobox,設定dbgrid1的oncolexit事件如下:

procedure tform1.dbgrid1colexit(sender: tobject);

begin

if dbgrid1.selectedfield.fieldname

= dbcombobox1.datafield then

begin

dbcombobox1.visible := false;

end;

end;

---- 6、 當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;

在Delphi中如何動態更改DBGrid的顏色

dbgrid控制項是乙個有許多使用者介面的顯示資料庫的控制項,以下的程式告訴您如何根據顯示的內容改變字型的顯示顏色。例如,如果乙個城市的人口大於200萬,我們就讓它顯示為藍色。使用的控制項事件為dbgrid.ondrawcolumecell.procedure tform1.dbgrid1drawc...

在Delphi的DBGrid中插入其他可視元件

delphi提供了功能強大的 dbgrid元件,以方便進行資料庫應用程式設計。但是如果我們僅僅利用dbgrid元件,每乙個獲得焦點 grid 只是乙個簡單的文字編輯框,不方便使用者輸入資料。delphi也提供了一些其他資料元件來方便使用者輸入,比如dbcombobox,dbcheckbox等元件,但...

delphi中的DBGRid滑鼠滾動事件

procedure onmousewheel var msg tmsg var handled boolean begin if msg.message wm mousewheel then begin if msg.wparam 0 then begin if dbgrid.focused the...