I’m trying to name columns (in this grey row) in a string grid. I know that I should use something like this:
procedure TForm1.FormCreate(Sender: TObject);
begin
StringGrid1.Cells[0,0] := 'Text 1';
StringGrid1.Cells[1,0] := 'Text 2';
end;
The problem is that there is error:
‘TForm1’ does not contain a member named ‘FormCreate’at line 81″.
I’m a beginner. What is wrong with my program?
asked Dec 5, 2013 at 18:30
1
You need to declare the method in the type.
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
...
end;
And that line of code to the declaration of the type that you will find near the top of your unit. Then your program will compile. You also need to make sure that the event handler attaches the handler to the form’s OnCreate
event. Use the Object Inspector to check that.
But the easiest way to make this all happen is to get the IDE to write it all. So, you would:
- Delete the code that you have shown in the question.
- Click on the form in the designer.
- Select the Events view in the Object Inspector.
- Find the
OnCreate
event in the Object Inspector. - Double click in the handler column of the
OnCreate
event in the Object Inspector. - Now the code editor opens showing an empty event handler body for you to add code to, and all the other parts are joined up. Specifically the method is declared in the type, and the handler is connected to the event.
Now, that’s how you do it normally, but it does pay to know the three things that need to be in place for an event to fire:
- The event handler is declared in the type of the class.
- The event handler is defined in the implementation of the class.
- The event handler is attached to the event in the Object Inspector. In fact, although you set it in the Object Inspector, the information actually lives in the .dfm file.
If you don’t know all this already, then asking questions on Stack Overflow is really not the most effective way to get up to speed. A good book would certainly help. Even if it’s for an older version of Delphi, the primary concepts have not changed for years. But if you don’t have a book, then you should at least follow the tutorial.
answered Dec 5, 2013 at 18:32
David HeffernanDavid Heffernan
602k42 gold badges1076 silver badges1491 bronze badges
0
Вам нужно объявить метод в типе.
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
...
end;
И эта строка кода для объявления типа, который вы найдете в верхней части вашего устройства. Тогда ваша программа скомпилируется. Вы также должны убедиться, что обработчик событий присоединяет обработчик к форме OnCreate
событие. Используйте инспектор объектов, чтобы проверить это.
Но самый простой способ добиться этого — заставить IDE написать все это. Итак, вы бы:
- Удалите код, который вы указали в вопросе.
- Нажмите на форму в дизайнере.
- Выберите представление «События» в Инспекторе объектов.
- Найти
OnCreate
событие в Инспекторе объектов. - Дважды щелкните в столбце обработчика
OnCreate
событие в Инспекторе объектов. - Теперь откроется редактор кода, показывающий пустое тело обработчика событий, к которому вы хотите добавить код, и все остальные части объединены. В частности, метод объявлен в типе, и обработчик связан с событием.
Вот как вы обычно это делаете, но стоит знать три вещи, которые должны быть в наличии для запуска события:
- Обработчик события объявляется в типе класса.
- Обработчик события определяется в реализации класса.
- Обработчик события присоединяется к событию в Инспекторе объектов. На самом деле, хотя вы установили его в Инспекторе объектов, информация фактически находится в файле.dfm.
Если вы еще этого не знаете, то задавать вопросы о переполнении стека — не самый эффективный способ набрать скорость. Хорошая книга, безусловно, поможет. Даже если это для более старой версии Delphi, основные концепции не менялись годами. Но если у вас нет книги, то вы должны по крайней мере следовать учебнику.
Topic: [SOLVED] (53,12) Fatal: Syntax error, «;» expected but «identifier TFORM1» found (Read 8941 times)
Continuing my quest….
I was creating a test to see if I finally got a grip on all this. Guess not…
I didn’t change TFORM1…
-
unit UnitRecTest;
-
{$mode objfpc}{$H+}
-
interface
-
uses
-
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls;
-
type
-
{ TForm1 }
-
TForm1 = class(TForm)
-
Edit1: TEdit;
-
Label1: TLabel;
-
procedure Edit1Change(Sender: TObject);
-
private
-
{ private declarations }
-
public
-
{ public declarations }
-
end;
-
var
-
Form1: TForm1;
-
code_str : string[28];
-
masterrec : record
-
status : longint;
-
shortname : string[8];
-
// company : code_str;
-
address : string[28];
-
city : string[28];
-
state : string[2];
-
zip : string[10];
-
POC : string[28];
-
tele : string[18];
-
shcomp : string[28];
-
shaddr : string[28];
-
shcity : string[28];
-
shstate : string[2];
-
shzip : string[10];
-
end;
-
implementation
-
{$R *.lfm}
-
{ TForm1 }
-
begin
-
procedure TForm1.Edit1Change(Sender: TObject); // ‘TFORM’ error on this line
-
begin
-
Edit1.Text:=masterrec.shortname;
-
end;
-
masterrec.shortname := ‘Blake’;
-
end.
The compiler doesn’t like code_str, either.
Other than that, I am having fun!!
Thanks!!
« Last Edit: September 19, 2016, 10:56:49 pm by WickedDum »
Logged
Practice Safe Computing!!
Intel i5-4460K @ 3.2GHz | Win8.1 64-bit | FPC: v3.0 | Lazarus: v1.6.0
Remove the statement «begin» in line 51 and you get a bit further
Logged
Thanks, Molly.
And take that BEGIN and insert it between lines 56 and 57. It compiles! It was a basic Pascal program structure error.
But
-
Edit1.Text:=masterrec.shortname;
does not display ‘Blake’. Any idea why not?
Thanks!
Logged
Practice Safe Computing!!
Intel i5-4460K @ 3.2GHz | Win8.1 64-bit | FPC: v3.0 | Lazarus: v1.6.0
does not display ‘Blake’. Any idea why not?
Hmz, strange that it even compiles as such.
Do you mind if i don’t answer the why but, instead provide two solutions ?
Solution 1:
Add an initialization section to your unit and place the initialization of your record field(s) in there.
Solution 2:
Implement the form event .formcreate (you can use the object inspector for that, select your form and click the events tab. In there is an event named onCreate. Double click the empty event filed to automatically let Lazarus create the code for this event inside your source. In that event (between the begin/end pair) initialize your record field(s).
edit:
For more information about structural organization of a unit, please read up inside the manual or on the wiki. That will also explain the initialization section and where to place.
« Last Edit: September 19, 2016, 09:17:09 am by molly »
Logged
Hmz, strange that it even compiles as such.
It should compile! Why are you surprised that it compiles? I just think it is strange because it does not display ‘Blake’.
Do you mind if i don’t answer the why but, instead provide two solutions ?
I don’t mind…but I would like to know. I believe you are leaning toward the lack of (proper/complete?) initialization? Although, I believe masterrec.shortname is initialized…
Solution 1:
Add an initialization section to your unit and place the initialization of your record field(s) in there.If I understand you correctly, you just want me to initialize the record. There is no Pascal ‘initialization’ section, correct?
Solution 2: …select your form and click the events tab…
I just double-clicked on the form itself and the template for TForm1.FormCreate was written. Is that where you want me to initialize everything? And, in the Events section, (none), FormCreate, and EditChange1 are the only options. Which one to I select? None appear to actually do anything…
I read the reference. Thanks. (Disregard INITIALIZATION concerns.)
Any idea why the compiler doesn’t like code_str?
Thanks for your time and suggestions!
« Last Edit: September 19, 2016, 09:45:41 am by WickedDum »
Logged
Practice Safe Computing!!
Intel i5-4460K @ 3.2GHz | Win8.1 64-bit | FPC: v3.0 | Lazarus: v1.6.0
Hmz, strange that it even compiles as such.
It should compile! Why are you surprised that it compiles? I just think it is strange because it does not display ‘Blake’.
It is strange as you have some code in the middle of an implementation section. afaik it should generate an error during compilation.
Do you mind if i don’t answer the why but, instead provide two solutions ?
I don’t mind…but I would like to know. I believe you are leaning toward the lack of (proper/complete?) initialization? Although, I believe masterrec.shortname is initialized…
Because the routine that initialized the field of the record isn’t called so your record field isn’t initialized either.
Solution 1:
Add an initialization section to your unit and place the initialization of your record field(s) in there.If I understand you correctly, you just want me to initialize the record. There is no Pascal ‘initialization’ section, correct?
There is, see also the links i put up in my edited post.
Solution 2: …select your form and click the events tab…
I just double-clicked on the form itself and the template for TForm1.FormCreate was written.
Good
Is that where you want me to initialize everything?
For learning purpose and you getting familair with things, yes. Later on the initialization of such record fields should belong to an event that is properly suited. You are not able to tell yet at this point in time.
If i do something like this, i add a button on a form and place my init code inside its onclick event in order to check if everything works as expected, then when a program matures, i place that code in an event that is more suited to the program.
And, in the Events section, (none), FormCreate, and EditChange1 are the only options. Which one to I select? None appear to actually do anything…
For storing a value inside your recrod field ? If yes, then inside the FormCreate event.
« Last Edit: September 19, 2016, 09:57:59 am by molly »
Logged
Oh, and something else….
You have it programmed now that in case user types something into edit1 that the same text of that edit box is changed to that what is stored inside your record field.
That is a bit awkward to say the least. You type something and then the text you type is being replaced. Not even sure if it works that way.
Logged
Any idea why the compiler doesn’t like code_str?
No idea. what is the error that the compiler tells you when you try to compile ?
edit: i bet you get a type error ;-p
You are trying to declare the type of a record field, but instead you assign it a variable.
« Last Edit: September 19, 2016, 10:08:15 am by molly »
Logged
And here some code that shows both ways of doing intialization.
Keep in mind though that indeed the moment you type something into the edit1 that the edit field text is changed into Blake (no matter what you type).
-
unit Unit1;
-
{$mode objfpc}{$H+}
-
interface
-
uses
-
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls;
-
type
-
{ TForm1 }
-
TForm1 = class(TForm)
-
Edit1: TEdit;
-
Label1: TLabel;
-
procedure Edit1Change(Sender: TObject);
-
procedure FormCreate(Sender: TObject);
-
private
-
{ private declarations }
-
public
-
{ public declarations }
-
end;
-
type
-
code_str = string[28];
-
var
-
Form1: TForm1;
-
// code_str : string[28];
-
masterrec :
-
record
-
status : longint;
-
shortname : string[8];
-
company : code_str;
-
address : string[28];
-
city : string[28];
-
state : string[2];
-
zip : string[10];
-
POC : string[28];
-
tele : string[18];
-
shcomp : string[28];
-
shaddr : string[28];
-
shcity : string[28];
-
shstate : string[2];
-
shzip : string[10];
-
end;
-
implementation
-
{$R *.lfm}
-
{ TForm1 }
-
procedure TForm1.Edit1Change(Sender: TObject);
-
begin
-
Edit1.Text := masterrec.shortname;
-
Label1.Caption := masterrec.address;
-
end;
-
procedure TForm1.FormCreate(Sender: TObject);
-
begin
-
masterrec.shortname := ‘Blake’;
-
end;
-
Initialization
-
begin
-
masterrec.address := ‘Planet earth’;
-
end;
-
end.
That should compile for you.
Logged
@molly — Thank you very much for your time. I understand your posts.
As for ‘Blake’ overwriting what is entered, I intended it only as a test to see if I assigned the edit1.text correctly. It didn’t display for me so that told me I failed. But it was only there as an in-house quick little test..
Thank you for your time and assistance (and code)!!!
Logged
Practice Safe Computing!!
Intel i5-4460K @ 3.2GHz | Win8.1 64-bit | FPC: v3.0 | Lazarus: v1.6.0
Oops…
The DEN error and, when I click continue, then:
Error reading Form1.OnCreate: Invalid value for property.
« Last Edit: September 19, 2016, 11:20:10 pm by WickedDum »
Logged
Practice Safe Computing!!
Intel i5-4460K @ 3.2GHz | Win8.1 64-bit | FPC: v3.0 | Lazarus: v1.6.0
Модератор: Модераторы
Ошибка Fatal: Syntax error, «;» expected
Доброго времени суток, препод дала задание, но при компиляции программа выдает ошибку «cloud.pas(51,12) Fatal: Syntax error, «;» expected but «identifier TFORM1″ found»
В код никакой отсебятины не добавлялось, полное копирование из задания.
- Код: Выделить всё
unit cloud;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, FileUtil, Buttons, ExtCtrls, StdCtrls;type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
PaintBox1: TPaintBox;
Timer1: TTimer;
procedure FormCreate(Sender: TObject);
private
{ private declarations }
//Координаты прорисовки объекта.Доступны всем процедурам класса TForm1
x1,y1:Integer;
public
{ public declarations }
//Процедура прорисовки облака
procedure Cloud(x,y:Integer; ColorCloud:TColor);
end;var
Form1: TForm1;implementation
{$R *.lfm}
procedure TForm1.FormCreate(Sender: TObject);
beginend;
{ TForm1 }
procedure TForm1.Cloud(x,y:Integer; ColorCloud:TColor);
begin
//Прорисовка облака из двух эллипсов
with PaintBox1.Canvas do begin
Pen.Style:=psClear;
Brush.Color:=ColorCloud;
Ellipse(x,y,x+80,y+40);
Ellipse(x+30,y+10,x+100,y+50);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
//установка начальных значений
x1:=0;
y1:=50;
Timer.Interval:=100;
//прорисовка картинки по которой двигается объект
PaintBox1.Canvas.Brush.Color:=clBlue;
PaintBox1.Canvas.Rectangle(0,0,PaintBox1.Width,PaintBox1.Height);
//Включение таймера-запуск анимации
Timer1.Enabled:=true;
end;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
//закраска объекта цветом фона
Cloud(x1,y1,clBlue)
//изменение координат прорисовки
x1:=x1+1;
//прорисовка объекта в новом месте
Cloud(x1,y1,clWhite);
end;
end.
Очень надеюсь на вашу помощь)
- Mire
- незнакомец
- Сообщения: 1
- Зарегистрирован: 03.05.2019 10:49:20
Re: Ошибка Fatal: Syntax error, «;» expected
Awkward » 04.05.2019 12:14:19
- Код: Выделить всё
procedure TForm1.Cloud(x,y:Integer; ColorCloud:TColor);
begin
//Прорисовка облака из двух эллипсов
with PaintBox1.Canvas do begin // <<<<< не парный begin
Pen.Style:=psClear;
Brush.Color:=ColorCloud;
Ellipse(x,y,x+80,y+40);
Ellipse(x+30,y+10,x+100,y+50);
end; // <<<<<< вставить
end;
- Awkward
- новенький
- Сообщения: 43
- Зарегистрирован: 19.01.2017 00:06:47
Re: Ошибка Fatal: Syntax error, «;» expected
iskander » 04.05.2019 12:29:38
И еще вот здесь:
- Код: Выделить всё
procedure TForm1.Button1Click(Sender: TObject);
begin
//установка начальных значений
x1:=0;
y1:=50;
Timer.Interval:=100;
//прорисовка картинки по которой двигается объект
PaintBox1.Canvas.Brush.Color:=clBlue;
PaintBox1.Canvas.Rectangle(0,0,PaintBox1.Width,PaintBox1.Height);
//Включение таймера-запуск анимации
Timer1.Enabled:=true;
//end; <-------- убрать лишний end
end;
- iskander
- энтузиаст
- Сообщения: 552
- Зарегистрирован: 08.01.2012 18:43:34
Re: Ошибка Fatal: Syntax error, «;» expected
VirtUX » 05.05.2019 11:27:40
Mire писал(а):procedure TForm1.Timer1Timer(Sender: TObject);
begin
//закраска объекта цветом фона
Cloud(x1,y1,clBlue); <—- тут пропустили «;»
//изменение координат прорисовки
x1:=x1+1;
//прорисовка объекта в новом месте
Cloud(x1,y1,clWhite);
end;
-
VirtUX - энтузиаст
- Сообщения: 878
- Зарегистрирован: 05.02.2008 10:52:19
- Откуда: Крым, Алушта
Вернуться в Lazarus
Кто сейчас на конференции
Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 2
От: | Аноним | ||
Дата: | 23.08.06 08:52 | ||
Оценка: |
procedure TForm1.FormCreate(Sender: TObject);
begin
Form1.Close;
end;
НЕ работает!!! Т.е. окно не закрывается! В пустом вновь созданном проекте!
Хотя с кнопки все работает.
Где можно было наплужить?
BDS 2006.
Re: Form1.Close не работает.
От: |
kochmin_alexandr
|
||
Дата: | 23.08.06 08:57 | ||
Оценка: |
А> procedure TForm1.FormCreate(Sender: TObject);
А> begin
А> Form1.Close;
А> end;
А> НЕ работает!!! Т.е. окно не закрывается! В пустом вновь созданном
А> проекте! Хотя с кнопки все работает.
кто тебя учил так писать код?
Этож надо додуматься в методе класса обращаться к экземпляру этого класса.
Вот из-за этого и считается что на дельфи только глючные программы бывают.
—
С уважением
Кочмин Александр
Posted via RSDN NNTP Server 2.1 beta
Re[2]: Form1.Close не работает.
От: | Аноним | ||
Дата: | 23.08.06 09:02 | ||
Оценка: |
Здравствуйте, kochmin_alexandr, Вы писали:
А>> procedure TForm1.FormCreate(Sender: TObject);
А>> begin
А>> Form1.Close;
А>> end;
А>> НЕ работает!!! Т.е. окно не закрывается! В пустом вновь созданном
А>> проекте! Хотя с кнопки все работает.
_>кто тебя учил так писать код?
Сам учился.
_>Этож надо додуматься в методе класса обращаться к экземпляру этого класса.
_>Вот из-за этого и считается что на дельфи только глючные программы бывают.
_>—
_>С уважением
_>Кочмин Александр
Раньше работало без проблем. Так что его в отдельную процедуру выносить?
Re: Form1.Close не работает.
От: |
Master Yoda
|
||
Дата: | 23.08.06 09:02 | ||
Оценка: |
Здравствуйте, <Аноним>, Вы писали:
А>procedure TForm1.FormCreate(Sender: TObject);
А>begin
А>Form1.Close;
А>end;
А>НЕ работает!!! Т.е. окно не закрывается! В пустом вновь созданном проекте!
А>Хотя с кнопки все работает.
Воспользуйся отладчиком. Зайди в метод Close. Убедись что форма не закрывается по той причине, что еще не проинициализирован Application.MainForm.
И какой цели ты собственно говоря хочешь добиться? Закрыть приложение? — Application.Terminate. Уничтожить форму? — Release. Скрыть форму? Вызови Hide в Form.OnShow
… << RSDN@Home 1.1.4 stable SR1 rev. 568>>
It is always bad to give advices, but you will be never forgiven for a good one.
Oscar Wilde
Re[2]: Form1.Close не работает.
От: | Аноним | ||
Дата: | 23.08.06 09:14 | ||
Оценка: |
Здравствуйте, Master Yoda, Вы писали:
MY>Здравствуйте, <Аноним>, Вы писали:
А>>procedure TForm1.FormCreate(Sender: TObject);
А>>begin
А>>Form1.Close;
А>>end;
А>>НЕ работает!!! Т.е. окно не закрывается! В пустом вновь созданном проекте!
А>>Хотя с кнопки все работает.
MY>Воспользуйся отладчиком. Зайди в метод Close. Убедись что форма не закрывается по той причине, что еще не проинициализирован Application.MainForm.
MY>И какой цели ты собственно говоря хочешь добиться? Закрыть приложение? — Application.Terminate. Уничтожить форму? — Release. Скрыть форму? Вызови Hide в Form.OnShow
Спасибо. Application.Terminate — работает.
А почему Form1.Close внезапно перестал работать?
Re[3]: Form1.Close не работает.
От: |
SeLarin
|
http://selarin.livejournal.com | |
Дата: | 23.08.06 10:16 | ||
Оценка: |
Здравствуйте, <Аноним>, Вы писали:
А>А почему Form1.Close внезапно перестал работать?
Он и не должен работать. В обработчике OnFormCreate ещё нет созданной формы Form1. Кстати, относительно первой ветки этой темы. Обращаться к экземпляру класса в методах класса нельзя, поскольку может быть несколько экземпляров одного и того же класса. Если ты в методе класс хочешь сослаться на экземпляр, для которого этот метод вызван, то используй специальное свойство Self. Например:
procedure TForm1.OnButtonClick(Sender: TObject);
begin
Self.Close;
end;
При нажатии на кнопку ты будешь закрывать ту форму, на которой расположена кнопка, даже если в приложении форм TForm1 несколько… Что произойдёт, если ты напишешь Form1.Close догадайся сам, в качестве упражнения.
… << RSDN@Home 1.2.0 alpha rev. 653>>
Re[3]: Form1.Close не работает.
От: |
White Barsik |
||
Дата: | 23.08.06 10:19 | ||
Оценка: |
Здравствуйте, Аноним, Вы писали:
А>А почему Form1.Close внезапно перестал работать?
А с чего вы взяли что он у вас работал? срабатывание и работа это не есть эквивалент. Случайно может быть как-то приводило к тем ожидаемым вами результатам.
Re[4]: Form1.Close не работает.
От: | Аноним | ||
Дата: | 23.08.06 11:40 | ||
Оценка: |
Здравствуйте, SeLarin, Вы писали:
SL>
SL>procedure TForm1.OnButtonClick(Sender: TObject);
SL>begin
SL> Self.Close;
SL>end;
SL>
А этот код не тоже самое сделает?
procedure TForm1.OnButtonClick(Sender: TObject);
begin
Close;
end;
Re[3]: Form1.Close не работает.
От: | Аноним | ||
Дата: | 23.08.06 12:17 | ||
Оценка: |
А>А почему Form1.Close внезапно перестал работать?
А в чём выразилась внезапность. Что случилось между тем как она работал, и тем как *внезапно* перестал ? www.rsdn.ru/HowToAsk.htm
PS: метод Close можно вызывать для созданных, существующих форм. Поэтому он работает в Button1Click и как повезёт — в OnCreate.
Аналогично метод Hide работает для видимых окон и не работает в OnShow, который вызывается в процессе ShowModal
Неудобно — но так оно есть.
Re[5]: Form1.Close не работает.
От: |
SeLarin
|
http://selarin.livejournal.com | |
Дата: | 23.08.06 16:14 | ||
Оценка: |
Здравствуйте, Аноним, Вы писали:
А>А этот код не тоже самое сделает?
А>
А>procedure TForm1.OnButtonClick(Sender: TObject);
А>begin
А> Close;
А>end;
А>
То же самое. Self ещё и неявно проставляться может . Я просто объяснял «на пальцах»…
Re: Form1.Close не работает.
От: | Аноним | ||
Дата: | 23.08.06 16:42 | ||
Оценка: |
Здравствуйте, Аноним, Вы писали:
А>procedure TForm1.FormCreate(Sender: TObject);
А>begin
А>Form1.Close;
А>end;
А>НЕ работает!!! Т.е. окно не закрывается! В пустом вновь созданном проекте!
А>Хотя с кнопки все работает.
А>Где можно было наплужить?
А>BDS 2006.
Попробуй поставить этот код на обработчик другого события…
- Переместить
- Удалить
- Выделить ветку
Пока на собственное сообщение не было ответов, его можно удалить.