孤独的猫

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

利用TdxDBTreeView控件(此处设为DBTreeMain)时,可以从表中直接显示出树结构,有时需要拖动对节点进行排序,而且数据表中有字段SortCode用于排序码,此时需要编写对应代码,步骤如下
1.先设置DBTreeMain的DragMode属性为dmAutomatic
2.设置DBTreeMain的StateIndexField属性为SortCode
3.在其OnEndDragTreeNode事件中写入
var
  m: TNodeAttachMode;
  oldOption: TdxDBTreeViewOptions;
  node: TdxDBTreeNode;
  bm: TBookmarkStr;
  idx: Integer;
begin
  inherited;
  try
    frmDragOption := TfrmDragOption.Create(nil);
    if frmDragOption.ShowModal = mrOK then
    begin
      //ShowMessage('1');
      if frmDragOption.rgOption.ItemIndex = 0 then
        m := naInsert
      else
        m := naAddChild;
      AttachMode := m;
      with DBTreeMain do
      begin
        oldOption := Options;
        Options := Options - [trCanDBNavigate];
        OnCompare := nil;
        bm := qryTree.Bookmark;
        qryTree.DisableControls;
        Items.BeginUpdate;
        try
          if m = naInsert then
          begin
            node := TdxDBTreeNode(Destination);
            idx := node.ImageIndex;
            UpdateSortCode(Source, idx);
            while node <> nil do
            begin
              Inc(idx, 10);
              UpdateSortCode(node, idx);
              node := TdxDBTreeNode(node.getNextSibling);
              if node = Source then
                Break;
            end;
          end
          else //添加子
          begin
            idx := GetChildMaxIdx(Destination) + 10;
            UpdateSortCode(Source, idx);
          end;
        finally
          Items.EndUpdate;
          Options := oldOption;
          OnCompare := DBTreeMainCompare;
          qryTree.EnableControls;
          qryTree.Bookmark := bm;
        end;
      end;
    end
    else
      //
  finally
    frmDragOption.Free;
  end;
end;

//UpdateSortCode过程
procedure TfrmSetTree.UpdateSortCode(ANode: TTreeNode; ASortCode: Integer);
var
  key: Variant;
begin
  key := TdxDBTreeNode(ANode).KeyFieldValue;
  with qryTree do
  begin
    if Locate('ID', key, []) then
    begin
      Edit;
      FieldByName('SortCode').AsInteger := ASortCode;
      Post;
    end;
  end;
  ANode.ImageIndex := ASortCode;
end;

//GetChildMaxIdx过程
function TfrmSetTree.GetChildMaxIdx(ANode: TTreeNode): Integer;
var
  i: Integer;
begin
  Result := 0;
  for i := 0 to ANode.Count - 1 do
  begin
    if ANode[i].ImageIndex > Result then
      Result := ANode[i].ImageIndex;
  end;
end;

4.在其OnCompare事件中写入
procedure TfrmSetTree.DBTreeMainCompare(Sender: TObject; Node1,
  Node2: TTreeNode; Data: Integer; var Compare: Integer);
begin
  inherited;
  if Node1.ImageIndex > Node2.ImageIndex then
    Compare := 1
  else if Node1.ImageIndex = Node2.ImageIndex then
    Compare := 0
  else
    Compare := -1;
end;

posted on 2009-02-27 21:15  孤独的猫  阅读(588)  评论(0编辑  收藏  举报