我有DBGrid
我在其中加载与DataSetPeople
关联的table_people
的名称。我创建了一个拖放过程,用户可以拖动名称并放入ListBox
。用户可以放入listbox_employees
或listbox_manager
。
我的问题
我想使用用户在两个列表框中放置的名称在table_people
之间创建关系。我创建table_relationship
employeeID
与managerID
匹配。
那么,如何从每个listbox
获取名称,将此名称与ID相关联,并将此ID放入与employeeID
或managerID
相关联的DataSetRelationship
到table_relationship
?
答案 0 :(得分:1)
如果您的ID是数字(整数)值,则可以在填充它时使用TListBox.Items.Objects
存储它(在表单上的放置事件处理程序中):
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;
答案 1 :(得分:0)
我希望您使用SQLite数据库制作表格。因此,您可以通过使用查询来插入行来实现。使用db.execSQL(); 你可以保留一个计数器来增加id值。