delphi cxGrid做一个空白的出/入库单

发布时间 2023-05-21 21:35:12作者: 一曲轻扬

效果图:

 实现的原理:

1.在数据库建一个表,然后绑定到cxgrid上面.数据表各字段的数据类型,按你的业务需求来设置,同时要允许空值,因为我们必须让它们保持空值,这样在绑定到cxgrid时,才会是空白的,然后再弄个自增的主键ID.下面这张图是我研究时截的图,不想改了,凑合着用吧

2.绑定过程略.

3.设置cxgrid表格为可编辑.

 

 4.在最左边新增一列,用来显示行号,不用绑定字段,但要写代码:

procedure TForm1.NumColGetDisplayText(Sender: TcxCustomGridTableItem;
  ARecord: TcxCustomGridRecord; var AText: string);
begin
AText := (ARecord.RecordIndex + 1).ToString;
end;

然后效果就出来了,最后再根据你的业务需要,设置一下哪些列可以选中,哪些列不可以选中.至于如何提交数据到数据库,无非就是各种拼装SQL语句.

 接下来,我们要完善用户输入的查询功能

设计图如下:

 两个查询控件,对应两个cxgrid,其中cxgrid2是显示查询结果的.Field1字段为用户输入的地方.绑定过程略

 

1.选中field1字段,然后设置Properties属性为:TextEdit

 2.然后在字段的事件列表中,找到OnChange事件:

 以下是代码:

procedure TForm1.GridViewJinHuoD_MXField1PropertiesChange(Sender: TObject);
var
  txt, isql: string;
  ARow: TcxCustomGridRow;
  ATop, ALeft: Integer;
begin
  txt := Trim(VarToStr(TcxTextEdit(Sender).EditingText));  //当前正在输入的值
  if txt.IsEmpty then
  begin
    cxGrid2.Visible := False;
    Exit;
  end;
{查询数据}
  with FDQueryCxGrid2 do
  begin
    Close;
    isql := 'select * from products where productCode like "%s" ' +
      'or  productName like  "%s" ' +
      'or  Model like  "%s" ' +
      'or  PYCode like  "%s" order by productCode limit 50';
    txt := '%' + txt + '%';  //不能在上面的isql中直接写成"%%s%",format会识别不了导致报错
    isql := Format(isql, [txt, txt, txt, txt]);
    sql.text := isql;
    Open();
    if IsEmpty then
      cxGrid2.Visible := False
    else
    begin
      ARow := tv.Controller.FocusedRow;
      if (ARow <> nil) and (ARow is TcxGridDataRow) then
      begin// 设置显示cxgrid2的位置
        ATop := ARow.ViewInfo.Bounds.Bottom; 
        ALeft := ARow.ViewInfo.Bounds.Left + NumCol.Width; // NumCol.Width是行号的列宽,要加上来.如果前面还有很多列,都按此操作;
        cxGrid2.Left := ALeft;
        cxGrid2.Top := ATop;
        cxGrid2.Visible := True;
      end
    end;
  end;
end;

这里我还遇到了一个坑,大家先不要着急往下看,不妨先想一想这是为什么?:

 我在大师群里问了很久,也没人回复我.然后我自己仔细想了一遍,会不会是事件冲突呢?于是我在所有事件中,全部都打上了断点,结果程序依然是没有被阻断,说明不是这里的问题.

接着我用cxgrid2来做试验,同样的代码,但是cxgrid2就是完全正常的啊!!!这是为什么??我总结了一下它和cxgrid1之间的不同,发现cxgrid2设置成了不可编辑,而cxgrid1是可编辑的,也就是说cxgrid1在被点击时,首先会进入到编辑状态,然后我看了一眼事件列表,最后豁然开朗

 

procedure TForm1.TVEditing(Sender: TcxCustomGridTableView; AItem:
  TcxCustomGridTableItem; var AAllow: Boolean);
begin
  cxGrid2.Visible := false;
end;

问题解决.最后,因为cxgrid1中,有些字段是不可以编辑的,所以我们还得保留单元格的点击事件:

procedure TForm1.TVCellClick(Sender: TcxCustomGridTableView;
  ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
  AShift: TShiftState; var AHandled: Boolean);
begin
   cxGrid2.Visible := false;
end;

功能到这里就差不多了,接下来无非就是用双击事件或者键盘判断用户在cxgrid2中的选择,然后把数据转到cxgrid1上面,这些比较简单,我就不写了,下面是最终的效果演示: