其他分享
首页 > 其他分享> > Delphi DBGrid 实现复选框

Delphi DBGrid 实现复选框

作者:互联网

1

在数据库对应的表中加入  bit 列验证是否被选中

然后dbgrid第一列的filedname是bit列

在DBgrid的onDrawColumnCell事件中写:

procedure 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); drawframecontrol(DBGrid1.Canvas.Handle,rect,dfc_button,ctrlstate[column.Field.asboolean]); end; end;

  

上方事件写完后会在第一行第一列出现复选框

 

 2

 在dbgrid的oncellclick事件中写,目的就是实现单击时  复选框被选中

procedure TcgDaohuodj.DBGrid1CellClick(Column: TColumn);
begin
  if DBGrid1.SelectedField.DataType=ftboolean   then
  begin
    DBGrid1.SelectedField.DataSet.Edit;
    DBGrid1.SelectedField.AsBoolean:=not DBGrid3.SelectedField.AsBoolean;
    DBGrid1.SelectedField.DataSet.Post;
  end;
end;

  

3
在dbgrid的ontitileclick事件中写如下代码,目的是点击bit列是实现全选和全消

 

procedure DBGrid1TitleClick(Column: TColumn);
var i:integer;
begin
  if column.Index=0 then begin    //验证是否第一列
    adoquery1.First;                //游标回滚
    DBGrid1.SelectedRows.CurrentRowSelected:=true;    //第一行被选中

    if trim(column.Title.Caption)='全选' then
    begin
      for i:=0 to dbgrid1.DataSource.DataSet.RecordCount-1 do
      begin
        dbgrid1.Fields[0].DataSet.edit;
        dbgrid1.Fields[0].AsBoolean:=true;
        dbgrid1.Fields[0].DataSet.post;
        dbgrid1.datasource.dataset.next;
      end;
      column.Title.Caption:='全消';
    end else begin
      for i:=0 to dbgrid1.DataSource.DataSet.RecordCount-1 do
      begin
        dbgrid1.Fields[0].DataSet.edit;
        dbgrid1.Fields[0].AsBoolean:=false;
        dbgrid1.Fields[0].DataSet.post;
        dbgrid1.datasource.dataset.next;
      end;
      column.Title.Caption:='全选';
    end;
    adoquery1.First;    //游标回滚
    DBGrid1.SelectedRows.CurrentRowSelected:=true;  //选中第一行
  end;
end;

 

 

效果如图:

 

标签:DBGrid,begin,end,column,Delphi,复选框,DBGrid1,dbgrid1,DataSet
来源: https://www.cnblogs.com/guorongtao/p/11947089.html