如何在delphi中使用TTreeview绑定数据以编辑控件

时间:2014-03-03 09:31:11

标签: delphi delphi-7

如何将数据从TTreeview控件绑定到Delphi中的Edit控件.. 当我点击提交按钮。就像我可以编辑那些数据并且必须更新它..

procedure TForm1.Button1Click(Sender: TObject);
var
  CurrentDeptID, RecordDeptID: Integer;
  RootNode, DeptNode: TTreeNode;
begin
  CurrentDeptID := 0;
  TreeList1.Items.Clear;
  RootNode := TreeList1.Items.Add(nil, 'Departments');
  DeptNode := nil;
  ADOQuery1.SQL.Text := 'SELECT sd.DeptID, sd.Name, d.Dept FROM SubDepartments sd INNER JOIN Departments d ON (sd.DeptID = d.DeptID) ORDER BY d.Dept, sd.Name';
  ADOQuery1.Open;
  try
    ADOQuery1.First;
    while not ADOQuery1.Eof do
    begin
      RecordDeptID := ADOQuery1.FieldByName('DeptID').AsInteger;
      if (DeptNode = nil) or (RecordDeptID <> CurrentDeptID) then
      begin
        DeptNode := TreeList1.Items.AddChild(RootNode, ADOQuery1.FieldByName('Dept').AsString);
        CurrentDeptID := RecordDeptID;
      end;
      TreeList1.Items.AddChild(DeptNode, ADOQuery1.FieldByName('Name').AsString);
      ADOQuery1.Next;
    end;
  finally
    ADOQuery1.Close;
  end;

谢谢..

1 个答案:

答案 0 :(得分:1)

在Delphi 7中没有DB Treeview作为标准,并且无论如何您的查询都是不可编辑的。如果要在表单上使用数据感知控件,则需要添加其他数据集以将编辑控件绑定到。您可以将子部门的密钥引用存储在TTreeItem的Data属性中。

procedure TForm1.Button1Click(Sender: TObject);
var
  CurrentDeptID, RecordDeptID: Integer;
  RootNode, DeptNode, SubDeptNode : TTreeNode;
begin
  CurrentDeptID := 0;
  TreeList1.Items.Clear;
  RootNode := TreeList1.Items.Add(nil, 'Departments');
  DeptNode := nil;
  ADOQuery1.SQL.Text := 'SELECT sd.DeptID, sd.Name, d.Dept FROM SubDepartments sd INNER JOIN Departments d ON (sd.DeptID = d.DeptID) ORDER BY d.Dept, sd.Name';
  ADOQuery1.Open;
  try
    ADOQuery1.First;
    while not ADOQuery1.Eof do
    begin
      RecordDeptID := ADOQuery1.FieldByName('DeptID').AsInteger;
      if (DeptNode = nil) or (RecordDeptID <> CurrentDeptID) then
      begin
        DeptNode := TreeList1.Items.AddChild(RootNode, ADOQuery1.FieldByName('Dept').AsString);
        CurrentDeptID := RecordDeptID;
      end;
      SubDeptNode := TreeList1.Items.AddChild(DeptNode, ADOQuery1.FieldByName('Name').AsString);
      SubDeptNode.Data := ADOQuery1.FieldByName('DeptID').AsInteger;
      ADOQuery1.Next;
    end;
  finally
    ADOQuery1.Close;
  end;

在Treeview的OnClick事件中,您可以恢复子部门的密钥并将该值传递给您的其他查询: -

Procedure TForm1.TreeList1Click(Sender : TObject);
Var
  lNode : TTreeNode;
  lID : Integer;
Begin
  lNode := TTreeList.Selected;
  If Assigned(lNode) And (lNode.Level = 2) Then
  Begin
    lID := lNode.Data;
    // Pass this lID to your additional query.
  End;
End;