如何在DBGrid中利用鼠标取得单元格的值

王朝other·作者佚名  2006-01-30
窄屏简体版  字體: |||超大  

如上3图所示,右键菜单里的选项随着鼠标指向的单元格数据不同而不同。如何实现呢?问题的关键在于如何取得鼠标指向的单元格的值。

查BCB帮助,看到DBGrid中有一方法:

TCustomGrid::MouseCoord

TCustomGrid See also

————————————————————————

Returns the row and column indexes of the cell that contains a point specified in screen coordinates.

struct TGridCoord

{

int X;

int Y;

};

TGridCoord __fastcall MouseCoord(int X, int Y);

Description

Call MouseCoord to locate the column and row of the cell which contains a given screen coordinate. Usually, MouseCoord is used to locate the cell that is under the mouse.

最后一句的大致意思是可以通过调用DBGrid的MouseCoord方法来取得单元格的行和列,但必须要知道单元格在屏幕中的坐标。通常地,MouseCoord事件被用取得鼠标指向的单元格的行和列。

只要知道了单元格的行和列就可以通过DBGrid->Columns->Items[]来取得单元格所属的字段的名称,而又可利用字段名来确定单元格中的值:Query->FieldByName(fieldname)->AsString。如何取得单元格在屏幕中的坐标?指向单元格的鼠标坐标就是需要的坐标。如何取得鼠标的坐标?利用DBGrid中的MouseMove事件,它将会传递出鼠标的坐标。一个解决方案生成:

DBGrid的Option:[dgTitles,dgColLines,dgRowLines,dgTabs,dgRowSelect,dgAlwaysShowSelection]

1、定义全局变量:

Add in .h file:

struct TGridCoord gc;

2、利用DBGrid的MouseMove事件获取鼠标坐标(MouseUp事件获取的鼠标坐标有时跟不上鼠标指针),

void __fastcall TForm1::DBGrid1MouseMove(TObject *Sender,TShiftState Shift, int X, int Y)

{

gc=DBGrid1->MouseCoord(X,Y); //通过MouseCoord将鼠标坐标转换成DBGrid的行和列

}

3、获取单元格值,改变右键菜单的选项:

void __fastcall TForm1::PopupMenu1Popup(TObject *Sender)

{

AnsiString fieldname;

fieldname=DBGrid1->Columns->Items[gc.X]->FieldName;//通过MouseCoord转换来的行进行取值,在鼠标右键点击单元格时,列的值即是数据库指针指向的当前记录

PopupMenu1->Items->Items[1]->Caption="查询 \""+Query1->FieldByName(fieldname)->AsString+"\"";

} TD.attachrow { BORDER-LEFT-COLOR: #000000; BORDER-BOTTOM-COLOR: #000000; FONT: 11px Verdana, Arial, Helvetica, sans-serif; COLOR: #000000; BORDER-TOP-COLOR: #000000; BORDER-RIGHT-COLOR: #000000 } TABLE.attachtable { BORDER-LEFT-COLOR: #000000; BORDER-BOTTOM-COLOR: #000000; FONT: 12px Verdana, Arial, Helvetica, sans-serif; COLOR: #000000; BORDER-TOP-COLOR: #000000; BORDER-COLLAPSE: collapse; BORDER-RIGHT-COLOR: #000000 }

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航