当前位置:天才代写 > tutorial > C语言/C++ 教程 > 在DBGrid中可选中行而又可进入编辑状态

在DBGrid中可选中行而又可进入编辑状态

2017-11-06 08:00 星期一 所属: C语言/C++ 教程 浏览:569

如安在DBGrid中选中行,而又让它可以进入编辑状态?

也许你会问我这有什么用?呵呵,做数据库应用的兄弟们会深有感伤,当用DBGrid显示的字段过多时,用户不得不拉动最下面的转动条,去看最右边的对象,假如没有配置DBGrid->Options[dgRowSelect],那么,拉到最右边之后,很有大概看串行的;假如配置了DBGrid->Options[dgRowSelect],则在拉到最右边之后,不会看串行,可是鼠标点击其它行(不是当前选中行)时,DBGrid的视图一下子就会回到显示最左边的那一列,确实很贫苦,用户不得纷歧次又一次的拖运下面的转动条。

焦点代码如下:

type
   TMyDBGrid=class(TDBGrid);
   //////////////////////////////////
//DBGrid1.Options->dgEditing=True
//DBGrid1.Options->dgRowSelect=False
   procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
   DataCol: Integer; Column: TColumn; State: TGridDrawState);
   begin
   with TMyDBGrid(Sender) do
   begin
 if DataLink.ActiveRecord=Row-1 then
 begin
 Canvas.Font.Color:=clWhite;
 Canvas.Brush.Color:=$00800040;
 end
 else
 begin
 Canvas.Brush.Color:=Color;
 Canvas.Font.Color:=Font.Color;
 end;
 DefaultDrawColumnCell(Rect,DataCol,Column,State);
   end;
   end;

他的办理步伐是:曲线救国,打消DBGrid->Options[dgRowSelect],把当前选中行的配景绘制成蓝色,就象是被选中一样,想法确实很妙。我们公司利用C++Builder,我只好把这段代码改为C++Builder版本的,这时,我才发明这段代码的精妙之处。

我发明DataLink属性是TCustomDBGrid中声明为protected的,而在DBGrid中并未声明它的可见性,因此,不能直接利用它;而Row属性则是在TCustomGrid中声明为protected的,在TCustomGrid的子类中也未声明它的可见性,那么,这段代码为安在Delphi中运行的很好?

原因就在于:ObjectPascal的单位封装,在同一个单位中界说的类,相互之间是友员的干系,我们再来看这段代码的开头:

type

TMyDBGrid = class(TDBGrid);

声明白一个TMyDBGrid类,那么,当前这个窗体类就和TMyDBGird类互为友元了,那么虽然当前窗体类可以直接会见TMyDBGrid的私有属性Row和DataLink了,一切都明白了,那么用C++就好实现了,焦点代码如下:

void __fastcall TMainForm::LineSelEdit(TObject *Sender,const TRect &Rect, int DataCol, TColumn *Column,TGridDrawState State)
   {
     class TMyGridBase : public TCustomGrid
     {
     public:
       __property Row;
     };
     class TMyGrid : public TCustomDBGrid
     {
     public:
       __property DataLink;
     };
     TMyGrid *MyGrid = (TMyGrid*)Sender;
     TMyGridBase *MyGridBase = (TMyGridBase*)Sender;
     TDBGrid *Grid = (TDBGrid*)Sender;
if(MyGrid->DataLink->ActiveRecord == MyGridBase->Row-1) {
Grid->Canvas->Font->Color = clWhite;
Grid->Canvas->Brush->Color = TColor(0x00800040);
     } else {
Grid->Canvas->Brush->Color = Grid->Color;
Grid->Canvas->Font->Color = Grid->Font->Color;
     }
Grid->DefaultDrawColumnCell(Rect,DataCol,Column,State);
   }

我把它封装成一个函数,函数的参数与DBGrid的OnDrawDataCell的参数一样,利用它的要领就是打消配置DBGrid->Options[dgRowSelect],然后配置DBGrid->DefaultDrawing = false,然后在这个DBGrid的OnDrawDataCell事件中挪用这个函数,如下:

void __fastcall TMainForm::DBGridDrawColumnCell(TObject *Sender,
const TRect &Rect, int DataCol, TColumn *Column,
      TGridDrawState State)
   {
this->LineSelEdit(Sender,Rect,DataCol,Column,State);
   }

 

    关键字:

天才代写-代写联系方式