3

I have 2 tables which are connected using master-detail connection. I need the connection reversed on creation of Form2 - so the master table becomes the detail table, and the detail table becomes the master table.

I tried doing this, and the program compiles, but doesn't work the way I want it to (the previous connection breaks, but it's not reversed, so the program kinda works like the tables aren't connected at all):

    Form1.ADOTableDetail.MasterSource.Destroy;
    Form1.ADOTableMaster.MasterSource :=  Form1.DataSourceDetail;
    Form1.ADOTableMaster.MasterFields := 'the_field_that_connects_them';

Any ideas on how I might achieve this?

Johan
  • 74,508
  • 24
  • 191
  • 319
Radiant
  • 47
  • 2
  • 10

3 Answers3

6

Don't destroy the MasterSource!

In order to break the relationship do

Form1.ADOTableDetail.MasterSource:= nil;
Form1.ADOTableDetail.MasterFields:= '';

than use this to reroute the MasterDetail

Form1.ADOTableMaster.MasterSource :=  Form1.DataSourceDetail;
Form1.ADOTableMaster.MasterFields := 'the_field_that_connects_them';

Also never call .Destroy directly, use .Free instead.
Free does an extra check to see if the reference you are Freeing is not nil, preventing some Access Violations.

Johan
  • 74,508
  • 24
  • 191
  • 319
  • @Radiant, thanks for re-accepting my answer, you seem torn between the two :-). *Damn now I've got that annoying song in my head*. – Johan May 23 '11 at 22:09
  • Hehe. No problem. Yes, I really was torn between which one I should accept - it's the hard part of being a StackOverflow user :D Anyways, I accepted your answer again, because NGLN's code gave me false sense of security. It could swap the relations only once, which I didn't notice. In the end I endedup writing my own sucky version of the code. I thank you both again, though! :D – Radiant May 23 '11 at 22:22
3
procedure TForm1.ExchangeMasterDetail;
begin
  ADOTableDetail.Close;
  ADOTableMaster.Close;
  ADOTableMaster.MasterFields := ADOTableDetail.IndexFieldNames;
  ADOTableMaster.IndexFieldNames := ADOTableDetail.MasterFields;
  ADOTableDetail.IndexFieldNames := '';
  ADOTableDetail.MasterFields := '';
  ADOTableDetail.MasterSource := nil;
  ADOTableMaster.MasterSource := DataSourceDetail;
  ADOTableDetail.Open;
  ADOTableMaster.Open;
end;
NGLN
  • 43,011
  • 8
  • 105
  • 200
0

Just set the Master table Active propriety to false.

Then do what you wanna todo and set it back to true.

Diosney
  • 10,520
  • 15
  • 66
  • 111
Samir
  • 1
  • 2