使用Delphi的DBGrid中的复选框编辑和显示布尔字段

本文介绍了如何在Delphi的DBGrid中通过复选框来编辑和显示布尔字段,以提供更友好的用户界面。尽管原始解决方案复杂且可能无法在点击复选框时正常工作,但Rene van der Heijden提出了一个简化的方法,只需要为DBGrid设置OnCellClick和OnCustomDrawCell事件处理器。
摘要由CSDN通过智能技术生成
Tip submitted by Rene van der Heijden Rene van der Heijden提交的提示

A series of articles titled Adding components to a DBGrid discusses placing just about any Delphi control (visual component) into a cell of a DGBrid. The idea is to create visually more attractive user interfaces for editing fields inside a DBGrid: a ComboBox for drop down lists; a DateTimePicker (calendar) for date values; a check box for boolean fields.

一系列名为“向DBGrid中添加组件”的文章讨论了将几乎任何Delphi控件(可视组件)放置到DGBrid的单元中的问题 。 这个想法是创建视觉上更具吸引力的用户界面来编辑DBGrid内的字段:ComboBox用于下拉列表; 日期时间的DateTimePicker(日历); 布尔字段的复选框。

布尔字段的复选框 ( CheckBox for Boolean Fields )

As noticed by Rene van der Heijden the solution is rather lengthy, and it doesn't work, at least not when using the mouse to click on the checkboxes.

正如Rene van der Heijden所注意到的那样,该解决方案相当冗长,并且无法正常工作,至少在使用鼠标单击复选框时无效。

Rene suggest an easier approach needing only two even handlers: OnCellClick and OnCustomDrawCell for your DBGrid control:

Rene建议使用一种更简单的方法,只需两个偶数处理程序:DBGrid控件的OnCellClick和OnCustomDrawCell:

//OnCellClik event of a DBGrid1
procedure TForm.DBGrid1CellClick(Column: TColumn) ;
begin
  if (Column.Field.DataType=ftBoolean) then
  begin
    {toggle True and False}
    Column.Grid.DataSource.DataSet.Edit;
    Column.Field.Value:= not Column.Field.AsBoolean;
   {immediate post - see for yourself whether you want this}
    Column.Grid.DataSource.DataSet.Post;
    {you may add additional functionality here,    to be processed after the change was made}
  end;
end;
//OnDrawColumnCell event of a DBGrid1
procedure TForm.DBGrid1DrawColumnCell(
  Sender: TObject;
  const Rect: TRect;
  DataCol: Integer;
  Column: TColumn;
  State: TGridDrawState) ;
const
  CtrlState: array[Boolean] of integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED) ;
begin
  if (Column.Field.DataType=ftBoolean) then
  begin
    DBGrid1.Canvas.FillRect(Rect) ;
    if VarIsNull(Column.Field.Value) then
      DrawFrameControl(DBGrid1.Canvas.Handle,Rect, DFC_BUTTON, DFCS_BUTTONCHECK or DFCS_INACTIVE) {grayed}
    else
      DrawFrameControl(DBGrid1.Canvas.Handle,Rect, DFC_BUTTON, CtrlState[Column.Field.AsBoolean]) ; {checked or unchecked}
  end;
end;

Delphi tips navigator:» Remove Duplicate Items in Delphi's TStringList« 5 Facts you Did Not Know about Delphi and Classes and the VCL and Inheritance and Custom Controls and...

Delphi提示导航器: »删除Delphi的TStringList中的重复项« 关于Delphi和类以及VCL和继承以及自定义控件和您不知道的5个事实...

翻译自: https://www.thoughtco.com/edit-display-boolean-fields-checkbox-dbgrid-1057927

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值