I have a datamodule for my frame, which uses a global instance.(dmData)
The data components are linked to the datasources on the dmData instance
now I want to use a datamodule instance that is private to a frame, because I want to have multiple instances of the form which contains the frame showing at the same time.
I can't figure out how to make that happen, either in code or in designing.
in the frame, I am creating the datamodule as dmLocalData := tdmData.Create(self), but in design I don't have the option to link dmLocalData, only the option to link to dmData(so all my data controls are blank (except for that ONE that has a local datasource that gets set in code)
I mean, in code, I could manually go through each component one by one and change the datasource, but thinking there really has to be a better way, the maintenance on that would be pretty much horrendous.
Any ideas about a better way?
Actually there is a way to avoid hand-wiring the controls for a dynamically created datamodule. In short - override the datamodules CreateNew constructor like this:
constructor TMainDM.CreateNew(AOwner: TComponent; Dummy: Integer);
begin
Dummy := -1;
inherited;
end;
This avoids that multiple instances of the datamodule get different names and thus the references are resolved as expected. As the datamodules are private to the frame anyway, there is no need for them to have globally unique names.
A much longer and more detailed explanation can be found in these two articles, which use a quite similar task as an example:
Tweaking DFM Loading (update)
Tweaking DFM Loading
In DPR file:
Application.CreateForm(TMain, Main);
Application.CreateForm(TCommStatus, CommStatus);
But I get an error if I want to use CommStatus in Main, because it was not instanced yet. Then inside TMain I tried:
procedure TMainWindow.FormShow(Sender: TObject);
begin
Application.CreateForm(TCommStatus, CommStatus);
CommStatus.Expand(Self);
end;
I was trying to have my LOG window to be positioned and sized according to my MainWindow position and width. But as my LOG window is created after Main Window, I can't really call it in OnCreate(), even because there is no correct positioning data in OnCreate().
Don't use Application.CreateForm to create the CommStatus form at all. Create it yourself in your MainWindow.OnCreate:
proccedure TMainForm.FormCreate(Sender: TObject);
begin
CommStatus := TCommStatus.Create(Self);
CommStatus.Expand(Self);
end;
Don't forget to remove CommStatus from the auto-create forms list (in Project->Options->Forms).
I need to know if CommStatus is Assigned before execute CreateForm.
You answered your own question - use Assigned(), eg:
uses
..., CommStatusFormUnit;
if not Assigned(CommStatus) then
Application.CreateForm(TCommStatus, CommStatus);
Or:
uses
..., CommStatusFormUnit;
if not Assigned(CommStatus) then
CommStatus := TCommStatus.Create(Application);
Global variables, like the CommStatus variable in the CommStatusFormUnit unit, are zero-initialized at program startup, thus Assinged() will return False until the form is actually created, as long as you assign the new Form instance to the global variable (as the examples above do).
But CommStatus identifier does not exists until it. So I can't use Assigned(CommStatus).
Yes, it does exist, and yes, you can use Assigned(CommStatus). If you are having errors with it, then you are not using it correctly.
Expand(Self) should use Main position information to put CommStatus beside Main in the same left position, but it doesn't.
Then you are not handling the positioning logic correctly.
Another option is to create CommStatus first in your DPR. But without using Application.CreateFom (which would then incorrectly make CommStatus you main form).
This way you'll know it has definitely been created, and not have to worry.
I.e.
CommStatus := TCommStatus.Create(Application);
Application.CreateForm(TMain, Main);
However, that fact that you're trying to Expand CommStatus in the OnShow of your main form seems a little dubious to me. You've created a hidden dependency between the two forms, which is exactly one of the reasons globals are frowned upon.
One option to clean that up would be as follows:
CommStatus := TCommStatus.Create(Application);
Application.CreateForm(TMain, Main);
CommStatus.Expand(Main);
This way the relationship between the two is explicit and less error-prone.
When I iterate of the controls on my form, I see those which I placed there at design time or run time. They are all of type TEdit, Tmemo, TComboBox, etc ...
However, there are always exactly eight which I do not recognize. I can skip over them, since they are not of a type which interests me, but I am curios.
I am guessing system controls like min/max/close. Their Name property is empty. Is there any way I can determine what type they are (without explicitly testing for every standard component derived from TWinControl) ?
I am curious - but not yellow ;-)
for i := 0 to Form1.ControlCount -1 do ...
Answer: use ClassName to find out. And i got TGrabHandle for all of them.
Thanks for all the help. +! all round
Use their ClassName to get an idea of wht they are when the Name property is empty.
TObject has the property ClassName; Try to access and interrogate this property for this components.
Paste the code block (for/while) that you are using for interrogate the form, for search components.
Regards
Working with my ongoing TFrames-based component set project, I'm coming across various instances where I am wanting to replace one of the TFrame's components (usually non-visual) at runtime with one that is generated dynamically at runtime.
I think I've probably found the answer to my immediate problem here, but in my own digging around and experimenting prior to finding that, it's become clear I've got quite a bit to learn about how Delphi handles object references, particularly with respect to forms/frames, and (in general) class properties which are object references rather than non-pointer values.
A specific example of one experiment is here:
(On a form with three TButtons)
procedure TForm1.Button3Click(Sender: TObject);
var
MyButton : TButton;
begin
MyButton := TButton.Create(Self);
MyButton.Caption := 'New Button';
MyButton.Parent := Form1;
Form1.Button2 := MyButton;
Form1.Repaint;
ShowMessage('Button2 caption = ' + Form1.Button2.Caption);
end;
Doesn't replace Button2 with the created button, but does show both on the form. The ShowMessage results indicates Button2's caption still = "Button2"
I find myself asking questions like, "Is this 'non-replacement' unique to forms, or would that be true for other classes as well?" etc. In short, I've discovered yet another sinkhole of my own ignorance. ;-) I find in working with instances/object references/derefencing/class definitions/class properties etc, that oftentimes things behave exactly as they expect them to, but other times, not at all, and not even close.
It's clear I need to study up on this area. Rather than post stupid question after stupid question revolving around this subject, I thought I'd ask this instead:
What is a really good reference or tutorial for getting a better grasp on the subtle distinctions re: how Delphi handles such things?
Thanks in advance for all your help!
Those fields on the forms are there purely for your convenience when writing code. You can delete them from the .pas file and they'd still show up. The form's layout is defined in the DFM, and the form object holds an internal list of references to the controls placed on it, just like any other visual control.
I don't know about tutorials on the subject, but I do know how you can replace a button. You've got it mostly right, but you also have to free Form1.Button2 before you overwrite the reference. That will cause the button to remove itself from the form's control list as part of its destruction process. Or, if you want to save the button somewhere instead of destroying it, call Form1.RemoveControl(Button2); instead.
I been reading bad things about the with keyword in delphi but, in my opinion, if you don't over use it. It can make your code look simple.
I often put all my TClientDataSets and TFields in TDataModules. So in my forms I had code like this
procedure TMyForm.AddButtonClick(Sender: TObject);
begin
with LongNameDataModule do
begin
LongNameTable1.Insert;
LongNameTable1_Field1.Value := "some value";
LongNameTable1_Field2.Value := LongNameTable2_LongNameField1.Value;
LongNameTable1_Field3.Value := LongNameTable3_LongNameField1.Value;
LongNameTable1_Field4.Value := LongNameTable4_LongNameField1.Value;
LongNameTable1.Post;
end
end;
without the with keyword I have to write the code like this
procedure TMyForm.AddButtonClick(Sender: TObject);
begin
LongNameDataModule.LongNameTable1.Insert;
LongNameDataModule.LongNameTable1_LongNameField1.Value := "some value";
LongNameDataModule.LongNameTable1_LongNameField2.Value :=
LongNameDataModule.LongNameTable2_LongNameField1.Value;
LongNameDataModule.LongNameTable1_LongNameField3.Value :=
LongNameDataModule.LongNameTable3_LongNameField1.Value;
LongNameDataModule.LongNameTable1_LongNameField4.Value :=
LongNameDataModule.LongNameTable4_LongNameField1.Value;
LongNameDataModule.LongNameTable1.Post;
end;
I think is easier to read using the with keyword.
Should I avoid using the with keyword?
The biggest danger of with, outside of pathological conditions like "with A, B, C, D" is that your code can silently change meaning with no notice to you. Consider this example:
with TFoo.Create
try
Bar := Baz;
DoSomething();
finally
Free;
end;
You write this code knowing that Bar is a property of TFoo, and Baz is a property of the type containing the method which has this code.
Now, two years later, some well-meaning developer comes in adds a Baz property to TFoo. Your code has silently changed meaning. The compiler won't complain, but the code is now broken.
The with keyword is a nice feature for making your code more readable but there are some pitfalls.
Debugging:
When using code like this:
with TMyClass.Create do
try
Add('foo');
finally
Free;
end;
There is no way to inspect the properties of this class, so always declare a variable and use the with keyword on that.
Interfaces:
When creating an interface in the with clause it lives till the end of your method:
procedure MemoryHog;
begin
with GetInterfaceThatTakes50MBOfMemory do
Whatever;
ShowMessage('I''m still using 50MB of memory!');
end;
Clarity
When using a class in a with clause that has properties or method names that already exists within the scope, it can fool you easily.
with TMyForm.Create do
Width := Width + 2; //which width in this with is width?
Of course when having duplicate names, you're using the properties and methods of the class declared in your with statement (TMyForm).
The with statement has its place but I have to agree that overuse can lead to ambiguous code. A good rule of thumb is to make sure the code is "more" readable and maintainable after adding the with statement. If you feel you need to add comments to explain the code after adding the statement then it is probably a bad idea. If the code is more readable as in your example then use it.
btw: this was always one of my favorite patterns in Delphi for showing a modal window
with TForm.Create(nil) do
try
ShowModal;
finally
Free;
end
I tend towards baning the with-statement altogether. As previously stated, it can make things complicated, and my experience is that it will. Many times the debugger want evaluate values because of withs, and all to often I find nested withs that lead to code that hard to read.
Brian's code seems readable and nice, but the code would be shorter if you just typecast the sender directly, and you remove all doubt about that component you enable:
TAction(Sender).Enabled := Something;
If you are concerned about typing to much, I prefare to make a temporary referance to the long-named object:
var
t: TTable;
begin
t := theLongNamedDataModule.WithItsLongNamedTable;
t.FieldByName(' ');
end;
I can't se why typing should bother you, though. We Are Typists First, Programmers Second, and code-completion, copy-paste and key-recording can help you be a more effective typist.
update:
Just stumbled over an long article with a little section on with-statements: he with keyword. The most hideous, dangerous, blow-your-own-feet-off feature in the language. :-)
When I first began pascal programming (with TurboPascal!) and learnt as I went, WITH seemed wonderful. As you say, the answer to tedious typing and ideal for those long records. Since Delphi arrived, I've been removing it and encouraging other to drop it - neatly summed-up by Verity at the register
Apart from a reduction in readability there are two main reasons why I'd avoid it:
If you use a class then you dont need it anyway - only records 'seem' to benefit from it.
Using the debugger to follow the code to the declaration with Ctrl-Enter doesnt work.
That said, for readability I still use the syntax:
procedure ActionOnUpdate( Sender : TObject )
begin
With Sender as TAction do
Enabled := Something
end;
I've not seen a better construct.
Your example, of a datamodule access within a button click, is a poorly contrived example in my opinion. The whole need for WITH goes away if you move this code into the data module where it should be. The OnClick then just calls LongNameDataModule.InsertStuff and there is no with needed.
With is a poor device, and you should look at your code to see why you are needing it. You probably did something wrong, or could do it a better way.
As Vegar mentioned, it's just as neat and much more readable, easier to debug, and less prone to stealth issues to use a temporary reference.
So far, I have never found a need to use with. I used to be ambivalent over it, until I took over a project that used the mind bending double with frequently. Questioning whether the original developer intended to reference items in the first with or second, if that ambiguous reference was a with-slip or clumsy code, the torment of trying to debug it, and the knock on effects of extending or modifying classes that use these abominations is just not worth anyone's time.
Explicit code is simply more readable. This way you can have your cake and enjoy eating it.
procedure TMyForm.AddButtonClick(Sender: TObject);
var
dm: TLongNameDataModuleType
begin
dm:=LongNameDataModule;
dm.LongNameTable1.Insert;
dm.LongNameTable1_Field1.Value := "some value";
dm.LongNameTable1_Field2.Value := LongNameTable2_LongNameField1.Value;
dm.LongNameTable1_Field3.Value := LongNameTable3_LongNameField1.Value;
dm.LongNameTable1_Field4.Value := LongNameTable4_LongNameField1.Value;
dm.LongNameTable1.Post;
end;
I'm a firm believer of removing WITH support in Delphi. Your example usage of using a datamodule with named fields is about the only instance I could see it working out. Otherwise the best argument against it was given by Craig Stuntz - which I voted up.
I just like to point out that over time you may eventually (should) rmeove all coding in OnClick events and your code will also eventually migrate away from named fields on datamodules into using classes that wrap this data and the reason to use WITH will go away.
Your question is an excellent example of 'a hammer is not always the solution'.
In this case, 'with' is not your solution: You should move this business logic out of your form into your datamodule.
Not doing so violates Law of Demeter like mghie (Michael Hieke) already commented.
Maybe your example was just illustrative, but if you are actually using code like that in your projects, this is what you should do in stead:
procedure TLongNameDataModule.AddToLongNameTable1(const NewField1Value: string);
begin
LongNameTable1.Insert;
LongNameTable1_Field1.Value := NewField1Value;
LongNameTable1_Field2.Value := LongNameTable2_LongNameField1.Value;
LongNameTable1_Field3.Value := LongNameTable3_LongNameField1.Value;
LongNameTable1_Field4.Value := LongNameTable4_LongNameField1.Value;
LongNameTable1.Post;
end;
And then call it from your form like this:
procedure TMyForm.AddButtonClick(Sender: TObject);
begin
LongNameDataModule.AddToLongNameTable1('some value');
end;
This effectively gets rid of your with statement, and makes your code more maintainable at the same time.
Of course surrounding Delphi strings with single quotes will help making it compile as well ;-)
The main problem with "with" is that you don't know where its scope ends, and you could have multiple overlapping with statements.
I don't think you should avoid using it, as long as your code is readable.
One of the proposals to make it more readable (and less confusing in longer code) was if codegear added the option to allow for aliases in with, and probably allowing multiple withs in one:
procedure TMyForm.AddButtonClick(Sender: TObject);
begin
with LongNameDataModule as dm, dm.LongNameTable1 as t1, dm.LongNameTable2 as t2 do
begin
t1.Insert;
t1.FieldByName('Field1').AsString := 'some value';
t1.FieldByName('Field2').AsString := t2.FieldByName('Field2').AsString;
t1.Post;
dm.Connection.Commit;
end
end;
As far as I'm concerned, With is quite acceptable in the case you give. It certainly improves the code clarity.
The real evil is when you have multiple with's open at once.
Also, my opinion is that what you are using the with on makes a big difference. If it's a truly different object then the with is probably a bad idea. However, I dislike having a lot of variables at one level even when this makes sense--generally data objects that hold an entire very complex data item--generally the entire piece of work the program is designed to work with. (I do not think this case would occur in an app that didn't have such an item.) To make the world clearer I often use records to group related items. I find that almost all withs I use are for accessing such subgroups.
There are many excelent answers here as to why the with statement is bad, so I'll try not to repeat them. I've been using the with statement for years and I'm very much starting to shy away from it. This is partially beause it can be difficult to work out scope, but I've been starting to get into refactoring lately, and none of the automated refactorings work withing a with statement - and automated refactoring is awesome.
Also some time ago I made a video on why the with statement is bad, it's not one of my best works but Here it is
Use with only temporarily (just as you comment-out temporarily).
It helps you write code sketches to get something compiled and running fast. If you consolidate the solution, clean it up! Remove with as you move code to the right place.
The current With statement is "dangerous", but it can be substantially improved:
With TForm1.Create (Nil) Do // New TForm1 instance
Try
LogForm ("); // That same instance as parameter to an outer method
"ShowModal; // Instance.ShowModal
Finally
"Free; // Instance.Free
End;
My proposal is:
No more than one object/record per With header.
Nested Withs not allowed.
Usage of " to indicate the object/record (double quotes are similar
to the ditto mark: http://en.wikipedia.org/wiki/Ditto_mark).