向 master-detail 添加新值时绑定外键 table Delphi

Binding a foreign key when adding a new value to the master-detail table Delphi

有 2 个 table 由主从链接。向详细信息table添加新值时,未绑定从主table选择的外键。

M-D 连接本身是在表单上执行的,分别使用两个 Dblookupcombobox 和 DataSource,每个 ADOQuery。 enter image description here

使用 [+] 按钮,添加组合框中不存在的新值。但是问题从第二个 [ + ] (aka detail)开始,当创建一个新行时,您需要它来绑定以前 LookUpComboBox (主)的外键。第二个按钮的按钮代码[+]:

begin
Form4.ADOQuery1.SQL.Clear;
Form4.ADOQuery1.SQL.Add('Select City from City WHERE   City='+#39+Form5.DBEdit1.Text+#39); //checking for duplicates
Form4.ADOQuery1.Open;
if Form4.ADOQuery1.IsEmpty then
  begin
  Form4.Query_city.FieldByName('City').AsString := Form5.DBEdit1.Text; //The PROBLEM is  SOMEWHERE HERE! It Adds a new value without binding the foreign key
  Form4.Query_city.Open;
  Form4.Query_city.Post;
  MessageBox(Handle, 'New data entered','Adding a new value',MB_ICONINFORMATION);
  end
 else
  begin
  Form4.Query_spec.Cancel;
  Form4.ADOQuery1.Cancel;
  MessageBox(Handle,PChar(''+Form5.DBEdit1.text+' already on the list!'),'Error',MB_ICONWARNING);
  end;
 end;

新值已写入 DBEdit1。它有一个对应的绑定到 tables。 那么如何使用相应的外键插入字段?

因为你的方式,你让这件事变得不必要的困难 代码是结构化的。尝试这样的事情:

打开 ADOQuery1,选择其全部内容,例如

procedure TForm4.OpenCitiesTable;
begin
  ADOQuery1.SQL.Clear;
  ADOQuery1.SQL.Add('Select City from City');
  ADOQuery1.Open;
end;

并在用户执行导致想要添加新城市的任何操作时保持打开状态。

然后,当用户想添加一个城市时,调用这个程序,例如供应城市 来自 Form5.DBEdit1.Text.

的值
procedure TForm4.AddCity(ACity : String);
begin
  ACity := Trim(ACity);  // remove any leading or trailing blanks
  //  Do any formatting checks on ACity here, re.g convert it to Proper case

  //  check for adding a duplicate
  if ADOQuery1.Locate('City', ACity, []) then begin
    ShowMessageFmt('%s is already in the City table', [ACity]);
    Exit;
  end;

  try
    ADOQuery1.Insert;
    ADOQuery1.FieldByName('City').AsString := ACity;
  finally
    ADOQuery1.Post;
    //  at this point you might want to refresh the contents of whatever source
    //  you are populating Form5.DBEdit1.Text from
  end;
end;

我假设你可以自己调整与TForm4.Query_spec相关的代码;

顺便说一句,您可能要考虑使用 TDBLookUpComboBox 而不是 DBEdit1。