2013-04-05 32 views
0

我有DBGrid,其中我加載的名字來自DataSetPeople,與table_people相關。我創建了一個拖放過程,用戶可以在其中拖動一個名稱並放入ListBox。用戶可以放入listbox_employeeslistbox_manager從ListBox到DataSet的數據

我的問題

我想用兩個列表框用戶下降的名稱創建一個從table_people人與人之間的關係。我創建了table_relationship,其中employeeIDmanagerID匹配。

所以,我怎樣才能得到每個listbox名字,聯想這個名字的ID,並把這個ID爲從DataSetRelationship相關聯table_relationship一個employeeIDmanagerID

回答

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; 
0

我希望你已經使用SQLite數據庫創建表。所以你想要做的是通過使用查詢來插入行。使用db.execSQL(); 你可以保留一個計數器來增加id值。

+0

我使用IBExpert(火鳥)。不需要計數器,employeeID是PK和FK,它是來自table_people的相同ID。通過這種方式,用戶不能將多個經理關聯到同一個員工。 – fmmatheus 2013-04-05 19:15:55