Argument out of range delphi ошибка

Can someone can explain me why i receive sometime an Exception «Argument out of range» under the ios simulator when i execute the code below? on android i never get any error. I use Delphi berlin.

the functions where the error appear :

{**********************************************************************}
procedure Twin_WorkerThreadPool.Enqueue(const Value: Twin_WorkerThread);
begin
  Tmonitor.Enter(fPool);
  try
    fPool.Add(Value);
    fSignal.SetEvent;
  finally
    Tmonitor.Exit(fPool);
  end;
end;

{********************************************************}
function Twin_WorkerThreadPool.Dequeue: Twin_WorkerThread;
begin
  Tmonitor.Enter(self); // << only one thread can execute the code below
  try

    Tmonitor.Enter(fPool);
    try
      if Fpool.Count > 0 then begin
        result := fPool[Fpool.Count - 1];
        fPool.Delete(Fpool.Count - 1);
        exit;
      end;
      fSignal.ResetEvent;
    finally
      Tmonitor.Exit(fPool);
    end;

    fSignal.WaitFor(Infinite);

    Tmonitor.Enter(fPool);
    try
      result := fPool[Fpool.Count - 1]; // << exception argument out of range ? but how it's possible ?
      fPool.Delete(Fpool.Count - 1);
    finally
      Tmonitor.Exit(fPool);
    end;

  finally
    Tmonitor.exit(self);
  end;
end;

Below the full source code :

  {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  Twin_WorkerThreadPool = class(TObject)
  private
    fPool: TObjectList<Twin_WorkerThread>;
    fSignal: Tevent;
  public
    procedure Enqueue(const Value: Twin_WorkerThread);
    function Dequeue: Twin_WorkerThread;
  end;

{***********************************}
constructor Twin_WorkerThread.Create;
begin
  FProc := nil;
  FProcReadySignal := TEvent.Create(nil, false{ManualReset}, false, '');
  FProcFinishedSignal := TEvent.Create(nil, false{ManualReset}, false, '');
  inherited Create(False); // see http://www.gerixsoft.com/blog/delphi/fixing-symbol-resume-deprecated-warning-delphi-2010
end;

{***********************************}
destructor Twin_WorkerThread.Destroy;
begin
  Terminate;
  FProcReadySignal.setevent;
  WaitFor;
  FProcReadySignal.Free;
  FProcFinishedSignal.Free;
  inherited;
end;

{**********************************}
procedure Twin_WorkerThread.Execute;
begin
  while True do begin
    try

      //wait the signal
      FProcReadySignal.WaitFor(INFINITE);

      //if terminated then exit
      if Terminated then Break;

      //execute fProc
      if assigned(FProc) then FProc();

      //signal the proc is finished
      FProcFinishedSignal.SetEvent;

    except
      //hide the exception
    end;
  end;
end;

{**********************************************************}
procedure Twin_WorkerThread.ExecuteProc(const AProc: TProc);
begin
  fProc := AProc;
  FProcFinishedSignal.ResetEvent;
  FProcReadySignal.SetEvent;
end;

{*****************************************************************}
procedure Twin_WorkerThread.ExecuteAndWaitProc(const AProc: TProc);
begin
  fProc := AProc;
  FProcFinishedSignal.ResetEvent;
  FProcReadySignal.SetEvent;
  FProcFinishedSignal.WaitFor(INFINITE);
end;

{********************************************************************}
constructor Twin_WorkerThreadPool.Create(const aThreadCount: integer);
var i: integer;
begin
  fPool := TObjectList<Twin_WorkerThread>.create(false{aOwnObjects});
  fSignal := TEvent.Create(nil, false{ManualReset}, false, '');
  for I := 0 to aThreadCount - 1 do
    fPool.Add(Twin_WorkerThread.Create)
end;

{***************************************}
destructor Twin_WorkerThreadPool.Destroy;
var i: integer;
begin
  for I := 0 to fPool.Count - 1 do begin
    fPool[i].disposeOf;
    fPool[i] := nil;
  end;
  fPool.Free;
  fSignal.Free;
  inherited Destroy;
end;

{*********************************************************************}
procedure Twin_WorkerThreadPool.ExecuteAndWaitProc(const AProc: TProc);
var aThread: Twin_WorkerThread;
begin
  aThread := Dequeue;
  try
    aThread.ExecuteAndWaitProc(aProc);
  finally
    Enqueue(aThread);
  end;
end;

NOTE:

Just to explain a little better, remember it’s only on ios it’s not work, and if i add a sleep(1000) after the fSignal.resetEvent then it’s work :

    Tmonitor.Enter(fPool);
    try
      if Fpool.Count > 0 then begin
        result := fPool[Fpool.Count - 1];
        fPool.Delete(Fpool.Count - 1);
        exit;
      end;
      fSignal.ResetEvent;

      sleep(1000);   

    finally
      Tmonitor.Exit(fPool);
    end;

    fSignal.WaitFor(Infinite);

so it’s look like that the signal is not set to OFF just after doing fSignal.ResetEvent;

i m affraid it’s a bug in TEvent or Tmonitor :(

demon-sheff

0 / 0 / 0

Регистрация: 21.03.2013

Сообщений: 47

1

18.08.2021, 13:21. Показов 4459. Ответов 22

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Здравствуйте.
Подскажите пожалуйста в чем может быть дело? Пишу планировщика заданий на Дельфи. В качестве базы использую аксес. На форму кинул DateTimePicker1 и DateTimePicker2 для просмотра заданий за определенный промежуток и кнопку. При нажатии на кнопку выходит сообщение Argument out of range.

Delphi
1
2
3
4
5
6
7
8
9
10
11
12
procedure TMain_Form.Button1Click(Sender: TObject);
var
  Present: TDateTime;       // сегодня
  NextDay: TDateTime;       // следующий день
  Year, Month, Day : Word;  // год, месяц, день
p1,p2:String;
  Begin
  ADOQuery1.SQL.Text:= 'SELECT * FROM Remind WHERE Beginning BETWEEN :p1 AND :p2';
  ADOQuery1.Parameters[0].Value := DateOf(DateTimePicker1.Date);
  ADOQuery1.Parameters[1].Value := DateOf(DateTimePicker1.Date);
  ADOQuery1.Open;
end;

В чем может быть дело?

Миниатюры

Ошибка: Argument out of range
 



0



D1973

Модератор

8505 / 5662 / 2293

Регистрация: 21.01.2014

Сообщений: 24,308

Записей в блоге: 3

18.08.2021, 13:43

2

А так?

Delphi
1
2
3
ADOQuery1.SQL.Text:= 'SELECT * FROM Remind WHERE Beginning BETWEEN :p1 AND :p2';
ADOQuery1.Parameters.ParamByName('p1').Value := DateTimePicker1.Date;
ADOQuery1.Parameters.ParamByName('p2').Value := DateTimePicker2.Date;

Добавлено через 2 минуты
Ну и, как бы, один и тот же день и в одном и во втором пикерах — это, как бы… Условие, ежели на русский перевести, будет выглядеть как «между сегодня и сегодня»… Тогда уж время надо указывать, а не дату…



0



0 / 0 / 0

Регистрация: 21.03.2013

Сообщений: 47

18.08.2021, 14:17

 [ТС]

3

Выдает ошибку

Миниатюры

Ошибка: Argument out of range
 



0



0 / 0 / 0

Регистрация: 21.03.2013

Сообщений: 47

18.08.2021, 14:21

 [ТС]

4

Ошибка
ADOQuery1: Parameter ‘p1’ not found
Хотя я их описал



0



5552 / 4335 / 1385

Регистрация: 14.04.2014

Сообщений: 19,406

Записей в блоге: 19

18.08.2021, 14:28

5

вы там случайно ни для чего еще раз не используете этот компонент?
тут почему-то общая практика все делать одним и тем же
для начала я бы написал
ADOQuery1.close;



0



Модератор

8505 / 5662 / 2293

Регистрация: 21.01.2014

Сообщений: 24,308

Записей в блоге: 3

18.08.2021, 14:55

6

Цитата
Сообщение от demon-sheff
Посмотреть сообщение

Хотя я их описал

Где? В диспетчере объектов? Не надо этого…



0



demon-sheff

0 / 0 / 0

Регистрация: 21.03.2013

Сообщений: 47

18.08.2021, 15:10

 [ТС]

7

Вот так должно быть?

Delphi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
procedure TMain_Form.Button1Click(Sender: TObject);
var
  Present: TDateTime;       // сегодня
  NextDay: TDateTime;       // следующий день
  Year, Month, Day : Word;  // год, месяц, день
  Begin
 // ADOQuery1.SQL.Text:= 'SELECT * FROM Remind WHERE Beginning BETWEEN :p1 AND :p2';
 // ADOQuery1.Parameters[0].Value := DateOf(DateTimePicker1.Date);
 // ADOQuery1.Parameters[1].Value := DateOf(DateTimePicker1.Date);
 
  ADOQuery1.SQL.Text:= 'SELECT * FROM Remind WHERE Beginning BETWEEN :p1 AND :p2';
  ADOQuery1.Parameters.ParamByName('p1').Value := DateTimePicker1.Date;
  ADOQuery1.Parameters.ParamByName('p2').Value := DateTimePicker2.Date;
  ADOQuery1.Open;
end;

ADOQuery1 используется только в этом моменте.
Ошибка с ADOQuery1: Parameter ‘p1’ not found сохраняется все равно

Добавлено через 5 минут

Цитата
Сообщение от krapotkin
Посмотреть сообщение

для начала я бы написал

ADOQuery1.close; пробовал ставить в начале ошибка та же



0



пофигист широкого профиля

4662 / 3096 / 855

Регистрация: 15.07.2013

Сообщений: 17,864

18.08.2021, 15:30

8

demon-sheff, вот тут случайно ничего не задано?

Миниатюры

Ошибка: Argument out of range
 



0



0 / 0 / 0

Регистрация: 21.03.2013

Сообщений: 47

18.08.2021, 15:45

 [ТС]

9

Цитата
Сообщение от northener
Посмотреть сообщение

вот тут случайно ничего не задано?

Нет, там пусто

Миниатюры

Ошибка: Argument out of range
 



0



Модератор

8505 / 5662 / 2293

Регистрация: 21.01.2014

Сообщений: 24,308

Записей в блоге: 3

18.08.2021, 15:47

10

поле Beginning в таблице БД какой тип имеет?



0



0 / 0 / 0

Регистрация: 21.03.2013

Сообщений: 47

18.08.2021, 15:58

 [ТС]

11

Цитата
Сообщение от D1973
Посмотреть сообщение

поле Beginning в таблице БД какой тип имеет?

Дата/Время



0



krapotkin

5552 / 4335 / 1385

Регистрация: 14.04.2014

Сообщений: 19,406

Записей в блоге: 19

18.08.2021, 16:26

12

что-то все равно от нас скрыто
поэтому чтобы не гадать
должно быть вот так

берем новый отдельный Query компонент
в дизайнере привязываем connection, заполняем свойство SQL и больше его не трогаем
в коде

Delphi
1
2
3
4
5
6
Query.Close();
Query.Parameters.ParamByName('p1').Datatype := ftDate;
Query.Parameters.ParamByName('p2').Datatype := ftDate; 
Query.Parameters.ParamByName('p1').Value := date1;
Query.Parameters.ParamByName('p2').Value := date2;
Query.Open();



0



demon-sheff

0 / 0 / 0

Регистрация: 21.03.2013

Сообщений: 47

18.08.2021, 17:59

 [ТС]

13

Проделал все как сказано, ничего не выводит:

Delphi
1
2
3
4
5
6
7
8
9
10
11
12
13
procedure TMain_Form.Button1Click(Sender: TObject);
var
  Present: TDateTime;       // сегодня
  NextDay: TDateTime;       // следующий день
  Year, Month, Day : Word;  // год, месяц, день
  Begin
  Query.Close();
  Query.Parameters.ParamByName('p1').Datatype := ftDate;
  Query.Parameters.ParamByName('p2').Datatype := ftDate;
  Query.Parameters.ParamByName('p1').Value := DateTimePicker1.Date;
  Query.Parameters.ParamByName('p2').Value := DateTimePicker2.Date;
  Query.Open;
end;

Миниатюры

Ошибка: Argument out of range
 



0



Модератор

8505 / 5662 / 2293

Регистрация: 21.01.2014

Сообщений: 24,308

Записей в блоге: 3

18.08.2021, 19:51

14

Гон какой-то… Один и тот же код на Дельфи7 отрабатывает, в RAD — ошибку эту самую кидает…

Миниатюры

Ошибка: Argument out of range
 

Ошибка: Argument out of range
 



0



5157 / 4110 / 1031

Регистрация: 29.08.2013

Сообщений: 26,084

Записей в блоге: 3

18.08.2021, 23:39

15

а если без имени параметра, а по его индексу?



0



пофигист широкого профиля

4662 / 3096 / 855

Регистрация: 15.07.2013

Сообщений: 17,864

18.08.2021, 23:59

16

Имхо, krapotkin, прав насчет того, что нужно явно указывать Datatype.



0



Модератор

8505 / 5662 / 2293

Регистрация: 21.01.2014

Сообщений: 24,308

Записей в блоге: 3

19.08.2021, 04:39

17

Цитата
Сообщение от northener
Посмотреть сообщение

нужно явно указывать Datatype

пробовал я так — та же песня: семерка — да, РАД 10.3 — нет…

Добавлено через 1 минуту

Цитата
Сообщение от qwertehok
Посмотреть сообщение

а по его индексу

тогда надо задавать список Parameters… Попробую — отпишусь…



0



Модератор

8505 / 5662 / 2293

Регистрация: 21.01.2014

Сообщений: 24,308

Записей в блоге: 3

19.08.2021, 05:18

18

Не, точно гон с этим акцессом… На работе РАД 10.4.1 — практически тот же самый код — и все отрабатывает…

Миниатюры

Ошибка: Argument out of range
 



1



0 / 0 / 0

Регистрация: 21.03.2013

Сообщений: 47

19.08.2021, 07:21

 [ТС]

19

То есть получается лучше перенести этот код на РАД 10.4.1?
Потому что у меня ХЕ5 и тоже не отрабатывает.



0



Модератор

8505 / 5662 / 2293

Регистрация: 21.01.2014

Сообщений: 24,308

Записей в блоге: 3

19.08.2021, 07:54

20

Цитата
Сообщение от demon-sheff
Посмотреть сообщение

То есть получается лучше перенести…

Я бы сказал так, что предпочтительней забыть про существование Access и перейти на нормальную СУБД. А чтобы работать с этими СУБД (FireBird, MySQL, SQLite — но это уже только для мелочей каких-нибудь) лучше, таки да, версию RAD Studio с FireDAC (по моему, как раз в XE5 появился…)



1



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

19.08.2021, 07:54

20

@ads69

When you have generated a Server and a client Project.
When launching the client, you can «Get» the table content, if you try to refresh the data you will get an Argument out of range exception.
Delphi 10.3.1 SQL Server database.

When you get all tables, all tables are checked, but when you have about 300 tables in your database and if you need only 3 tables it’s a pain to check only those you don’t want.
It would ne nice to have a check all/ uncheck all function in the tool.
amazing work.

@FMXExpress

Workaround:
If you experience a EArgumentOutOfRangeException copy the Delphi FMX.Grid.Style.pas source file to your project directory and change the two raise lines in the CellRect event to Exit as follows:

function TStyledGrid.CellRect(const ACol, ARow: Integer): TRect;
var
I, X, Y: Integer;
HiddenFound: Boolean;
begin
if (ACol < 0) or (ACol > ColumnCount) then
Exit;//raise EArgumentOutOfRangeException.CreateResFmt(@SInvalidColumnIndex, [ACol]);
if (ARow < 0) or (ARow > RowCount) then
Exit;//raise EArgumentOutOfRangeException.CreateResFmt(@SInvalidRowIndex, [ARow]);

@ads69

Thanks for your reply.
Unfortunatelly it doesn’t solve the problem.
I still get the error.

But When I add an exit on this line I have no error :

procedure TMainForm.RefreshTable;
var
I: Integer;
ColumnCount: Integer;
ColumnWidth: Integer;
begin
  if Closing then Exit;
  --->exit;

Добрый день!

Установил XE8, открыл проект собранный на XE7

начались проблемы со стилями (если использовать один стиль на всех формах), это пол беды. пришлось стиль новый для каждой формы ставить…

а ошибка что в названии появилась откуда не ждал, есть TListView, заполняется динамически

1-зачение добавляем

 ListView1.ClearItems;
  with ListView1.Items.Add do
  begin
    Text := 'KCell';
    Bitmap.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'kcell.png'));
    Tag := 3;
  end;
  with ListView1.Items.Add do
  begin
    Text := 'Activ';
    Bitmap.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'activ.png'));
    Tag := 391;
  end;
  with ListView1.Items.Add do
  begin
    Text := 'Tele2';
    Bitmap.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'tele2.png'));
    Tag := 125;
  end;
  with ListView1.Items.Add do
  begin
    Text := 'Pathword';
    Bitmap.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'pathword.png'));
    Tag := 73;
  end;
  with ListView1.Items.Add do
  begin
    Text := 'Beeline';
    Bitmap.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'beeline.png'));
    Tag := 90;
  end;
  with ListView1.Items.Add do
  begin
    Text := 'ДОС';
    Bitmap.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath,
      'beeline-dos.png'));
    Tag := 578;
  end;
  with ListView1.Items.Add do
  begin
    Text := 'Dalacom';
    Bitmap.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'dalacom.png'));
    Tag := 12;
  end;
  with ListView1.Items.Add do
  begin
    Text := 'City';
    Bitmap.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'city.png'));
    Tag := 134;
  end;
  with ListView1.Items.Add do
  begin
    Text := 'ALTEL 4G';
    Bitmap.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'altel4g.png'));
    Tag := 716;
  end;
  with ListView1.Items.Add do
  begin
    Text := 'АО "Казахтелеком"';
    Bitmap.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'telecom.png'));
    Tag := 0;
  end;

2-значение

ListView1.ClearItems;
  with ListView1.Items.Add do
  begin
    Text := 'ALTEL 4G';
    Bitmap.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'altel4g.png'));
    Tag := 716;
  end;
  with ListView1.Items.Add do
  begin
    Text := 'JET';
    Bitmap.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'jet.png'));
    Tag := 484;
  end;
  with ListView1.Items.Add do
  begin
    Text := '"Интернет Дома" от Beeline';
    Bitmap.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath,
      'internetdoma.png'));
    Tag := 413;
  end;

моделируем ситуацию

если грузим 1 значение и тыкаем (выделяем) на последний или больший 2 itemindex

затем выполняем 2 значение, то выскакивает

argument out of range

т.е. получается ItemIndex или Selected Item не сбрасывается.

как эту ошибку исправить?

6 / 6 / 8

Регистрация: 18.09.2014

Сообщений: 124

1

28.10.2014, 22:47. Показов 14734. Ответов 10


Проблема такая. У меня программа через FTP качает файл с данными о версии. Читает. Сравнивает. И если версии такая же что и у оригинала, то просто запускает дальнейшую программу. Если же не такая же, то удаляет все старые файлы (кроме программы обновления, та что работает), а потом скачивает все файлы. Посмотрите код. Скажите что не так.

Delphi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
procedure DELETED; stdcall; external 'loader.dll';
procedure TForm3.FormCreate(Sender: TObject);
var
addr,vers,or_vers,fn:string;
l,l2:tstringlist;
i:integer;
begin
idftp1.Host:='IP';
idftp1.Username:='nik';
idftp1.Password:='parolchik';
idftp1.Port:=21;
idftp1.Connect;
  idftp1.Get('/radoc/ver.vinf','ver.vinf');
    l:=Tstringlist.Create;
    l.LoadFromFile('ver.vinf');
    vers:=l.Values['vers'];
    l.Destroy;
      DeleteFile('ver.vinf');
      if FileExists('or_ver.vinf') then
      begin
      l.LoadFromFile('or_ver.vinf');
      or_vers:=l.Values['vers'];
      if vers=or_vers then
        begin
          RichEdit1.Lines.Add('Обновлений не обноружено');
          WinExec('RADoc.exe',SW_Show);
        end
          else
            begin
  l.Clear;
  l.Add(vers);
  DELETED;               //dll библиотека (обновляеться)
  idftp1.ChangeDir('/radoc/load');
  idftp1.List;
  RichEdit1.Lines.Add('Download strat...');
    for I := 2 to idftp1.DirectoryListing.Count do
      begin
        fn:=idftp1.DirectoryListing.Items[i].FileName;
        idftp1.Get('/radoc/load/'+fn,fn);
        RichEdit1.Lines.Add('Download: '+fn);
      end;
        if FileExists('RADoc.exe') then
          WinExec('RADoc.exe',SW_Show);
            end;
      end
        else
          begin
            ShowMessage('Не обноружен файл or_ver.vinf'+#13+#10+'Пожалуйста свяжитесь с разработчиком!');
          end;
end;

Вот код Dll

Delphi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
library loader;
 
uses
  Winapi.Windows,
  Winapi.Messages,
  System.SysUtils,
  System.Variants,
  System.Classes,
  Vcl.Graphics,
  Vcl.Controls,
  Vcl.Forms,
  Vcl.Dialogs,
  Vcl.StdCtrls,
  IdBaseComponent,
  IdComponent,
  IdTCPConnection,
  IdTCPClient,
  IdExplicitTLSClientServerBase,
  IdFTP,
  Vcl.ComCtrls,
  Vcl.Menus,
  Vcl.Buttons;
 
{$R *.res}
procedure SHOWMSG_ERROR; stdcall; export;
begin
  ShowMessage('ERROR');
end;
 
procedure DELETED; stdcall; export;
begin
DeleteFile('config.propertis');
DeleteFile('RADoc.exe');
DeleteFile('save.stfra');
DeleteFile('style.vsf');
end;
 
  Exports DELETED;
begin
end.

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

0

На чтение 6 мин. Просмотров 127 Опубликовано 15.12.2019

Добрый день друзья. Использую данный метод в своей игре:

Он генерирует слово, разбивает на символы, в случайном порядке их расставляет. Здесь переменная Word определена, в итоге и переменная Hint и Path приходит с кнопки, события OnClick.
Первый раз, при запуске сцены, метод отрабатывает хорошо, без ошибок.

После того, как слово отгадано, я обнуляю все переменные другим методом

В итоге жму на кнопку с уже другими переменными Word, Hint, Path и вываливается ошибка:

ArgumentOutOfRangeException: Argument is out of range.
Parameter name: index

Не могу понять, в чём проблема и почему так происходит. Первые строчки точно отрабатывают нормально, так как меняется Path.

Подскажите пожалуйста, что не так делаю, всю голову сломал. Спасибо огромное заранее!

I’m using a TListBox in Firemonkey, and I’m facing a strange issue when it comes to dynamically showing/hiding items. This includes both Delphi XE7 and XE8. The setup, there is a TPopupBox at the top of the form, where user chooses one of the items listed. Depending on which was chosen, the TListBox should show only certain TListBoxItem s, and hide the rest. Part of this consists of resizing each list item height to 0 when not visible (otherwise it would leave an ugly gap between the items).

The problem is that very randomly and spontaneously (no pattern), selecting an item in this TPopupBox (calling OnChange which modifies visibility), produces an EArgumentOutOfRangeException at an unknown point. The code breaks in System.Generics.Collections.TListHelper.SetItemN() on the first line calling CheckItemRangeInline(AIndex); Within there, it’s simply:

The exception continues to be raised over and over and over again with no end (starts with 4 in a row). When I use the debugger to step in, I can never manage to get it to happen.

There are a couple common procedures used here which control item visibility:

Then, when choosing something in the TPopupBox :

(The full procedure is just a lot of the exact same types of calls, too much to post here)

  1. Nowhere am I adding or removing items — only changing visibility
  2. There are no events triggered which might be causing some faulty loop
  3. The TPopupBox is located outside of the TListBox
  4. Each TListBoxItem has one or two controls (yet it doesn’t matter which ones are being shown/hidden)
  5. Selecting an item in this TPopupBox may work one time, yet fail the next
  6. Sometimes it occurs the first time I show/hide these items, sometimes it takes 20-30 tries
  7. Never able to reproduce while stepping through in Debug

Why would I be receiving this exception, and how do I fix it?

Давно не было статей об исправлении ошибок, и вот настало время. Разбираться мы будем с ошибкой out of range на мониторе. Поговорим том, что это такое, о причинах возникновения и методах исправления этой ошибки.

Содержание

  1. Ошибка out of range
  2. Причины ошибки out of range на мониторе
  3. Как исправить ошибку out of range
  4. Как убрать out of range – второй монитор
  5. Решение ошибки out of range через безопасный режим
  6. Out of range из-за проблем с драйверами
  7. Out of range из-за неисправности оборудования
  8. Пример из жизни

Out of range (рус. вне диапазона) – это ошибка указывающая на то, что сигнал получаемый от видеокарты не входит в рабочий диапазон сигналов монитора.

Причины ошибки out of range на мониторе

Существует несколько причин возникновения такой ошибки:

  • Изменение частоты обновления экрана на не поддерживаемую монитором.
  • Изменения разрешения экрана на не поддерживаемое монитором.
  • Проблемы с драйверами видеокарты или монитора.
  • Ошибки в работе видеокарты или монитора.

Самые распространенные причины ошибки out of range – первые две, когда монитор не поддерживает разрешение экрана или частоту установленную видеокартой. Такое часто бывает со старым мониторами, или при ручном изменении частоты экрана. Реже выявляются ошибки с драйверами.

Как исправить ошибку out of range

Вот мы и подошли к самой главной части этой статьи, к решению проблемы с out of range на мониторе. Существует несколько возможных способов исправить эту ошибку. Начнем, пожалуй, сразу с самого действенного.

Как убрать out of range – второй монитор

Да это один из почти 100% методов исправления ошибки out of range, если драйвера не при чем, но не у всех есть возможность им воспользоваться, так как нужен второй монитор или телевизор.

1. Подключаете компьютер к другому монитору или домашнему телевизору.

2. Меняете частоту обновления и разрешение экрана на низкие значения, точно поддерживаемые вашим основным монитором.

3. Подключаете компьютер к первому монитору и проверяете. Если всё в порядке, меняете значения частоты и разрешения экрана на поддерживаемые вашим монитором.

Решение ошибки out of range через безопасный режим

Второй способ это использование безопасного режима Windows.

1. Перезагрузите компьютер в безопасном режиме.

2. Измените частоту и разрешение экрана на поддерживаемые вашим монитором.

3. Перезагрузите компьютер, чтобы проверить решило ли это вашу проблему.

Совет: если изменение параметров не сохраняется при загрузке в обычном режиме, заходите в безопасный режим через «режим VGA» («Базовое видео» в Windows 10).

Out of range из-за проблем с драйверами

Другая причина появления ошибки out of range/вне диапазона, это проблемы с драйверами. И если предыдущие способы не помогают, мы рекомендуем переустановить драйвера видеокарты и монитора.

1. Загрузите компьютер в безопасном режиме.

2. Откройте Диспетчер устройств (нажмите Win+Pause, и в левой верхней части окна выберите нужную нам утилиту).

3. В Диспетчере устройств разверните разделы «Видеоадаптеры» и «Мониторы», затем удалите каждое из устройств находящееся в этих разделах. Это можно сделать, выделив устройство и нажав клавишу Delete или кликнув правой кнопкой мыши и выбрав «Удалить».

4. Далее перезагрузите компьютер и позвольте Windows переустановить драйвера для этих устройств, или установите их вручную.

Out of range из-за неисправности оборудования

Бывает и такое, что оборудование ломается или работает неправильно. Один из способов проверить, что вызывает ошибку, монитор или видеокарта, это подключение вашего монитора к другому компьютеру и подключение вашего компьютера к другому монитору.

Пример из жизни

Напоследок вот вам пример из жизни, который и натолкнул нас на написание этой статьи. К нам обратился пользователь Александр с таким сообщением:

«Задал слишком высокую частоту обновления экрана, в результате чего при запуске Виндовс пишет out of range.

Прочитал что надо в безопасном режиме удалить драйвер видеокарты, так и сделал, все запустилось, но после того как я снова устанавливаю драйвер, снова пишет out of range. Как теперь быть?»

После некоторой переписки, в конце концов, Александру помог метод с подключением компьютера к другому монитору или телевизору и уменьшение частоты обновления и разрешения экрана.

Using Delphi 10.4.
I am hoping someone can explain what I am doing wrong with my FMX TTreeView that is causing an EArgumentOutOfRangeException. I am trying to create a custom TTreeViewItem class that allows me to associate some data with each node, as well as provide an in-place editor to allowing changing the node text.

The code below is a stripped down version of what I am doing. The FMX form has a TTreeview and two buttons on it, with the form’s Onshow set to FormShow and the buttons set to the two button events.

The TVLinkTreeViewItem is my custom TTreeViewItem where I add a background and edit component for my in-place editor, which is displayed when a node is double clicked.

When you run the code as is, the program will throw the exception when the logic gets to the TreeView1.EndUpdate call at the end of the FormShow routine. The exception is thrown in FMX.Controls in the TControl.EndUpdate procedure.

If you comment out the ExpandAll call, the exception is not thrown, but if you mess with the expanding and collapsing of the nodes and resizing of the form, sooner or later the exception gets thrown. I left the ExpandAll line in the code below, as I assume the exception is being caused by the same error.

From what I can tell, the problem appears to be how I am setting up the fBackground and fEditor. If I don’t call the AddObject routine and not set the Parent properties, I get no exception.

So can anybody tell me what I am doing wrong? Or is there a better way to do an in-place editor for the FMX TTreeViewItems component?

unit Unit1;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.TreeView, FMX.Layouts, FMX.Controls.Presentation,
  FMX.MultiView, FMX.Edit, FMX.Objects, FMX.StdCtrls;

type
  TForm1 = class(TForm)
    TreeView1: TTreeView;
    Button1: TButton;
    Button2: TButton;
    procedure FormShow(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.fmx}

type
  TVLinkTreeViewItem = class(TTreeViewItem)
  private
    fData: string;
    fEditor: TEdit;
    fBackground: TRectangle;
    procedure TreeViewItem1DblClick(Sender: TObject);
    procedure EditorExit(Sender: TObject);
    procedure EditorKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
  public
    property Editor: TEdit read fEditor write fEditor;
    property Data: string read fData write fData;
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  TreeView1.ExpandAll;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  TreeView1.CollapseAll;
end;

procedure TForm1.FormShow(Sender: TObject);
var
  I, c, r, s: Integer;
  vNode1,
  vNode2,
  vNode3,
  vNode4: TVLinkTreeViewItem;
begin
  TreeView1.BeginUpdate;
  TreeView1.Clear;
  for I := 0 to 4 do
    begin
      vNode1 := TVLinkTreeViewItem.Create(TreeView1);
      vNode1.Text := 'Level 1 - '+ IntToStr(I);
      TreeView1.AddObject(vNode1);
      for c := 0 to 4 do
        begin
          vNode2 := TVLinkTreeViewItem.Create(vNode1);
          vNode2.Text := 'Level 2 - '+ IntToStr(c);
          vNode1.AddObject(vNode2);
          for r := 0 to 4 do
            begin
              vNode3 := TVLinkTreeViewItem.Create(vNode2);
              vNode3.Text := 'Level 3 - '+ IntToStr(r);
              vNode2.AddObject(vNode3);
//              for s := 0 to 4 do
//                begin
//                  vNode4 := TVLinkTreeViewItem.Create(vNode3);
//                  vNode4.Text := 'Level 4 - '+ IntToStr(s);
//                  vNode3.AddObject(vNode4);
//                end;
            end;
        end;
    end;
  //ExpandAll works when no parent is set for fBackGround and fEditor is not set in "TVLinkTreeViewItem.Create" below"
  //If the Parents are set below, ExpandAll/EndUpdate causes "Augument out of range" exception.
  TreeView1.ExpandAll;
  treeView1.EndUpdate;
end;

{ TVLinkTreeViewItem }

constructor TVLinkTreeViewItem.Create(AOwner: TComponent);
begin
  inherited;
  fData := '';
  fBackground := TRectangle.Create(AOwner);
  //When ExpandAll is not called in FormShow,
  //   Calling "AddObject" or setting parent, as shown below, make all the code work,
  //   but will get intermident "Augument out of range" exceptions when resizing form,
  //   or when expanding or collapsing nodes using the buttons.
  self.AddObject(fBackGround);
  //fBackGround.Parent := self;
  fBackGround.Visible := false;
  fEditor := TEdit.Create(AOwner);
  fBackGround.AddObject(fEditor);
  //fEditor.Parent := fBackGround;
  fEditor.Visible := false;
  fEditor.Align := TAlignLayout.Client;
  fEditor.OnKeyDown := EditorKeyUp;
  self.OnDblClick := TreeViewItem1DblClick;
  fEditor.OnExit := EditorExit;
end;

destructor TVLinkTreeViewItem.Destroy;
begin

  inherited;
end;

procedure TVLinkTreeViewItem.TreeViewItem1DblClick(Sender: TObject);
begin
  fBackGround.Visible := true;
  fBackGround.Width := self.Width - 20;
  fBackGround.Height := self.Height;
  fBackGround.Position.X := 20;
  fEditor.Enabled := true;
  fEditor.Visible := true;
  fEditor.Opacity := 1;
  fBackGround.BringToFront;
  fEditor.BringToFront;
  fEditor.Text := Text;
  fEditor.SetFocus;
  fEditor.SelectAll;
end;

procedure TVLinkTreeViewItem.EditorKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
  inherited;
  if Key = vkReturn then
    begin
      Text := fEditor.Text;
      fBackGround.Visible := false;
      fEditor.Enabled := false;
    end
  else if Key in [vkEscape, vkCancel, vkTab, vkHardwareBack] then
    begin
      fBackGround.Visible := false;
      fEditor.Enabled := false;
    end;
end;

procedure TVLinkTreeViewItem.EditorExit(Sender: TObject);
begin
  fBackGround.Visible := false;
  fEditor.Enabled := false;
  fEditor.Visible := false;
end;

end.

Here’s the fmx content:

object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form1'
  ClientHeight = 480
  ClientWidth = 640
  FormFactor.Width = 320
  FormFactor.Height = 480
  FormFactor.Devices = [Desktop]
  OnShow = FormShow
  DesignerMasterStyle = 0
  object TreeView1: TTreeView
    Align = Left
    Size.Width = 269.000000000000000000
    Size.Height = 480.000000000000000000
    Size.PlatformDefault = False
    TabOrder = 0
    Viewport.Width = 265.000000000000000000
    Viewport.Height = 476.000000000000000000
  end
  object Button1: TButton
    Position.X = 356.000000000000000000
    Position.Y = 68.000000000000000000
    TabOrder = 2
    Text = 'Expand'
    OnClick = Button1Click
  end
  object Button2: TButton
    Position.X = 354.000000000000000000
    Position.Y = 102.000000000000000000
    TabOrder = 1
    Text = 'Collapse'
    OnClick = Button2Click
  end
end

@ads69

When you have generated a Server and a client Project.
When launching the client, you can «Get» the table content, if you try to refresh the data you will get an Argument out of range exception.
Delphi 10.3.1 SQL Server database.

When you get all tables, all tables are checked, but when you have about 300 tables in your database and if you need only 3 tables it’s a pain to check only those you don’t want.
It would ne nice to have a check all/ uncheck all function in the tool.
amazing work.

@FMXExpress

Workaround:
If you experience a EArgumentOutOfRangeException copy the Delphi FMX.Grid.Style.pas source file to your project directory and change the two raise lines in the CellRect event to Exit as follows:

function TStyledGrid.CellRect(const ACol, ARow: Integer): TRect;
var
I, X, Y: Integer;
HiddenFound: Boolean;
begin
if (ACol < 0) or (ACol > ColumnCount) then
Exit;//raise EArgumentOutOfRangeException.CreateResFmt(@SInvalidColumnIndex, [ACol]);
if (ARow < 0) or (ARow > RowCount) then
Exit;//raise EArgumentOutOfRangeException.CreateResFmt(@SInvalidRowIndex, [ARow]);

@ads69

Thanks for your reply.
Unfortunatelly it doesn’t solve the problem.
I still get the error.

But When I add an exit on this line I have no error :

procedure TMainForm.RefreshTable;
var
I: Integer;
ColumnCount: Integer;
ColumnWidth: Integer;
begin
  if Closing then Exit;
  --->exit;

Добрый день!

Установил XE8, открыл проект собранный на XE7

начались проблемы со стилями (если использовать один стиль на всех формах), это пол беды. пришлось стиль новый для каждой формы ставить…

а ошибка что в названии появилась откуда не ждал, есть TListView, заполняется динамически

1-зачение добавляем

 ListView1.ClearItems;
  with ListView1.Items.Add do
  begin
    Text := 'KCell';
    Bitmap.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'kcell.png'));
    Tag := 3;
  end;
  with ListView1.Items.Add do
  begin
    Text := 'Activ';
    Bitmap.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'activ.png'));
    Tag := 391;
  end;
  with ListView1.Items.Add do
  begin
    Text := 'Tele2';
    Bitmap.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'tele2.png'));
    Tag := 125;
  end;
  with ListView1.Items.Add do
  begin
    Text := 'Pathword';
    Bitmap.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'pathword.png'));
    Tag := 73;
  end;
  with ListView1.Items.Add do
  begin
    Text := 'Beeline';
    Bitmap.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'beeline.png'));
    Tag := 90;
  end;
  with ListView1.Items.Add do
  begin
    Text := 'ДОС';
    Bitmap.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath,
      'beeline-dos.png'));
    Tag := 578;
  end;
  with ListView1.Items.Add do
  begin
    Text := 'Dalacom';
    Bitmap.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'dalacom.png'));
    Tag := 12;
  end;
  with ListView1.Items.Add do
  begin
    Text := 'City';
    Bitmap.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'city.png'));
    Tag := 134;
  end;
  with ListView1.Items.Add do
  begin
    Text := 'ALTEL 4G';
    Bitmap.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'altel4g.png'));
    Tag := 716;
  end;
  with ListView1.Items.Add do
  begin
    Text := 'АО "Казахтелеком"';
    Bitmap.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'telecom.png'));
    Tag := 0;
  end;

2-значение

ListView1.ClearItems;
  with ListView1.Items.Add do
  begin
    Text := 'ALTEL 4G';
    Bitmap.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'altel4g.png'));
    Tag := 716;
  end;
  with ListView1.Items.Add do
  begin
    Text := 'JET';
    Bitmap.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'jet.png'));
    Tag := 484;
  end;
  with ListView1.Items.Add do
  begin
    Text := '"Интернет Дома" от Beeline';
    Bitmap.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath,
      'internetdoma.png'));
    Tag := 413;
  end;

моделируем ситуацию

если грузим 1 значение и тыкаем (выделяем) на последний или больший 2 itemindex

затем выполняем 2 значение, то выскакивает

argument out of range

т.е. получается ItemIndex или Selected Item не сбрасывается.

как эту ошибку исправить?

Возможно, вам также будет интересно:

  • Arerr 9388 ошибка аутентификации
  • Arena of valor ошибка 554827811
  • Are you writing your essay at the moment найти ошибку
  • Are you welsh ошибка
  • Are you older of your brother где ошибка

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии