0

我有DBGrid我将名称从DataSetPeople关联加载到table_people. 我创建了一个拖放过程,用户可以在其中将名称拖放到ListBox. 用户可以放入 alistbox_employeeslistbox_manager

我的问题

table_people我想通过使用用户在两个列表框中放置的名称来创建人与人之间的关系。我创建table_relationshipwhere employeeIDmatch with managerID

那么,如何从 each 中获取名称listbox,将此名称与 ID 相关联,并将此 ID 放入 aemployeeIDmanagerIDfrom DataSetRelationshipassociated to 中table_relationship

4

2 回答 2

1

如果您的 ID 是数字(整数)值,您可以TListBox.Items.Objects在填写时使用 来存储它(在表单上的 drop 事件处理程序中):

var
  PersonName: string;
  PersonID: Integer;
begin
  with YourDataModule do  // Gives access to the tables in the data module
  begin
    PersonName := table_people.FieldByName('employeeName').AsString;
    PersonID   := table_people.FieldByName('employeeID').AsInteger);
  end;
  listbox_employees.Items.AddObject(PersonName, TObject(PersonID);
end;

对于经理,只需更改为经理的列表框和经理的字段值。

要获取 ID 以用于INSERT语句:

// Make sure both listboxes have the same number of items, of course.
var
  EmployeeID: Integer;
  ManagerID: Integer;
  i: Integer;
begin
  for i := 0 to ListBox_Employees.Items.Count - 1 do
  begin
    EmployeeID := Integer(ListBox_Employees.Items.Objects[i]);
    ManagerID := Integer(ListBox_Manager.Items.Objects[i]);
    if not YourDataModule.MakeRelationship(EmployeeID, ManagerID) then
      ShowMessage('Unable to relate this employee and manager!');
  end;
end;

// If you're using a SQL query, the `INSERT` should be created like this
// somewhere, like in your datamodule's OnCreate event
//   qryRelationShips.SQL.Clear;
//   qryRelationShips.SQL.Add('INSERT INTO table_relationship (employeeID, managerID)');
//   qryRelationShips.SQL.Add('VALUES (:employeeID, :managerID)';
//
// Or you can type it into the SQL property in the Object Inspector at designtime 
//   INSERT INTO table_relationship (employeeID, managerID) VALUES (:employeeID, :managerID)


function TYourDataModule.MakeRelationship(const EmpID, MgrID: Integer):  Boolean;
begin
  Result := False;
  // INSERT into your dataset:
  qryRelationShips.ParamByName('employeeID').AsInteger := EmpID;
  qryRelationShips.ParamByName('managerID').AsInteger := MgrID;
  try
    qryRelationShips.ExecSQL;
    Result := qryRelationShips.RowsAffected;
  finally
    qryRelationShips.Close;
  end;
end;

// If you're using a table instead of a query, getting a result is harder
function TYourDataModule.MakeRelationship(const EmpID, MgrID: Integer):  Boolean;
begin
  Result := True;
  try
    tblRelationShips.Insert;
    tblRelationShips.FieldByName('employeeID').AsInteger := EmpID;
    tblRelationShips.FieldByName('managerID').AsInteger := MgrID;
    tblRelationShips.Post;
  except
    Result := False;
  end;
end;
于 2013-04-05T19:55:16.957 回答
0

我希望你已经使用 SQLite 数据库制作了表格。因此,您可以通过使用查询插入行来实现。使用 db.execSQL(); 您可以保留一个计数器来增加 id 值。

于 2013-04-05T19:06:10.293 回答