i posted a question on Fixing an error in a method declaration in a form in Delphi but after getting it fixed another error popped up upon compiling and its saying project project1.exe raised exception class EStringListError with message ‘list index out of bounds(0)’.when i press continue its not working but when i press break its flashing on the code neraz:=true;
this is my code below
Procedure Reload;
var
i:integer;
begin
form1.ListBox1.Clear;
form1.ListBox2.Clear;
if neraz then
HD;
neraz:=true;//..................here
form1.Label3.Caption:='free: '+inttostr(vs*32)+' byte'+#10#13+'cluster size = 32 bytes';
i:=TABLE[nk1].nach;
KolP1:=0; KolP2:=0;
while (FAT[i]<>1024) do begin
if TABLE[fat[i]].tip then begin
form1.ListBox1.Items.Add('dir>'+TABLE[fat[i]].name);
inc(kolP1);
end
else
if TABLE[fat[i]].format='txt' then
form1.ListBox1.Items.Add('f_text> '+TABLE[fat[i]].name+'.'+TABLE[fat[i]].format)
else
form1.ListBox1.Items.Add('f_bin> '+TABLE[fat[i]].name+'.'+TABLE[fat[i]].format);
if (fat[i]<>0) then
i:=fat[i];
end;
i:=TABLE[nk2].nach;
while (FAT[i]<>1024) do begin
if TABLE[FAT[i]].tip then begin
form1.ListBox2.Items.Add('dir>'+TABLE[fat[i]].name);
inc(kolP2)
end
else
if TABLE[fat[i]].format='txt' then
form1.ListBox2.Items.Add('f_text> '+TABLE[fat[i]].name+'.'+TABLE[fat[i]].format)
else
form1.ListBox2.Items.Add('f_bin> '+TABLE[fat[i]].name+'.'+TABLE[fat[i]].format);
if (fat[i]<>0) then
i:=fat[i];
end;
vfail;
end;
procedure HD;
var
i: integer;
begin
for i := 0 to 49 do begin
with form2.ListView1.Items[i] do begin
SubItems[0] := TABLE[i].name;
SubItems[1] := TABLE[i].format;
if TABLE[i].tip then
SubItems[2] := 'folder'
else
SubItems[2] := 'file';
SubItems[3] := IntToStr(TABLE[i].nach);
SubItems[4] := IntToStr(TABLE[i].razmer);
end;
form2.ListView2.Items[i].SubItems[0] := IntToStr(fat[i]);
end;
end;
asked Jan 8, 2012 at 15:45
Mildred ShimzMildred Shimz
5874 gold badges10 silver badges20 bronze badges
4
The exception class EStringListError raises the error List index out of bounds (0) when you try to access a member of a TStrings instance that is empty. The most likely candidate for that is the SubItems property of the list items.
You would appear to have fallen into quite a common trap. Although you have created columns for the list view, you also need to fill out the SubItems list for each list item. A simple solution is to modify HD like this:
with form2.ListView1.Items[i] do begin
while SubItems.Count<5 do
SubItems.Add('');
SubItems[0] := ...
Although it may in fact be better to add the sub-items at the same time that you create the list items. But I’m not showing code for that since you didn’t include the part of your program that populates the lists.
answered Jan 8, 2012 at 16:38
![]()
David HeffernanDavid Heffernan
595k42 gold badges1052 silver badges1470 bronze badges
0
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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 |
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, ComCtrls; type TForm1 = class(TForm) OpenDialog1: TOpenDialog; SaveDialog1: TSaveDialog; MainMenu1: TMainMenu; ColorDialog1: TColorDialog; N1: TMenuItem; N2: TMenuItem; N3: TMenuItem; N4: TMenuItem; N5: TMenuItem; N6: TMenuItem; N7: TMenuItem; procedure N4Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; Buff: TBitmap; mas: array of integer; Lmas:integer; bw: integer; bh: integer; LStr: integer; Nbit: integer; Clr: TColor; implementation {$R *.dfm} procedure Ris1; var i, j, m, k, a, b: integer; {ïåðåìåííûå íåîáõîäèìûå â êà÷åñòâå ñ÷åò÷èêîâ, à òàêæå äëÿ ïðîìåæóòî÷íûõ âû÷èñëåíèé} begin if Lmas<>0 then {âûïîëíÿåì äåéñòâèÿ ïî îòîáðàæåíèþ äàííûõ, åñëè äëèíà âõîäíîãî ìàññèâà íå ðàâíà íóëþ} begin PatBlt(Buff.Canvas.Handle,0,0,Buff.Width,Buff.Height,blackness); {î÷èñòêà áèòîâîé ìàòðèöû ïóòåì ðèñîâàíèÿ íà íåé ÷åðíîãî ïðÿìîóãîëüíèêà} Buff.Canvas.Pen.Color := Clr; {çàäàåì öâåò äëÿ ðèñîâàíèÿ åäèíè÷íûõ ýëåìåíòîâ} for i := 1 to ((Form1.Width-10) div bh) do {îðãàíèçóåì öèêë îò åäèíèöû äî ÷èñëà ñòðîê, ïîìåùàþùèõñÿ íà ýêðàíå} begin for m := 0 to bh-1 do {îðãàíèçóåì öèêë â ñîîòâåòñòâèè ñ ìàñøòàáîì ïî âåðòèêàëè} begin k := i*LStr-1+Nbit; {âû÷èñëÿåì íîìåð ýëåìåíòà â ìàññèâå mas, ÿâëÿâøåãîñÿ ïîñëåäíèì â ïðåäûäóùåé ñòðîêå} b := bh*i+m+10; {âû÷èñëÿåì çíà÷åíèå êîîðäèíàòû ïî îñè y îòîáðàæàåìîé ñòðîêè ýëåìåíòîâ} for j := 1 to LStr do {îðãàíèçóåì öèêë ïî âñåì ýëåìåíòàì ñòðîêè îò ïåðâîãî äî LStr} begin inc(k); {âû÷èñëÿåì íîìåð k ýëåìåíòà ìàññèâà mas, êîòîðûé äîëæåí áûòü îòîáðàæåí} if k>=Lmas then break; {åñëè î÷åðåäíîé íîìåð ýëåìåíòà ìàññèâà mas ïðåâûøàåò ëèáî ðàâåí äëèíå ìàññèâà Lmas, òî öèêë îòîáðàæåíèÿ áóäåò çàâåðøåí; äàííîå óñëîâèå âûïîëíÿåòñÿ ïðè âûâîäå íà ýêðàí íåïîëíîé ïîñëåäíåé ñòðîêè} if mas[k] = 1 then {åñëè k-é ýëåìåíò ìàññèâà åäèíèöà, òî ðèñóåì ëèíèþ äëèíû bw çàäàííûì öâåòîì} begin a := 10+j*bw; Buff.Canvas.MoveTo(a-bw, b); Buff.Canvas.LineTo(a, b); end; end; end; end; Form1.Canvas.Draw(0, 0, Buff); {êîïèðóåì áèòîâóþ ìàòðèöó íà êàíâó ôîðìû} end; end; procedure Ris2; var i, j, k: integer; {ïåðåìåííûå íåîáõîäèìûå â êà÷åñòâå ñ÷åò÷èêîâ, à òàêæå äëÿ ïðîìåæóòî÷íûõ âû÷èñëåíèé} begin if Lmas<>0 then {âûïîëíÿåì äåéñòâèÿ ïî îòîáðàæåíèþ äàííûõ, åñëè äëèíà âõîäíîãî ìàññèâà íå ðàâíà íóëþ} begin PatBlt(Buff.Canvas.Handle,0,0,Buff.Width,Buff.Height,blackness); {î÷èñòêà áèòîâîé ìàòðèöû ïóòåì ðèñîâàíèÿ íà íåé ÷åðíîãî ïðÿìîóãîëüíèêà} Buff.Canvas.Font.Color := Clr; {çàäàåì öâåò äëÿ îòîáðàæåíèÿ åäèíè÷íûõ è íóëåâûõ ýëåìåíòîâ} Buff.Canvas.Brush.Color := clBlack; {çàäàåì öâåò ôîíà} for i := 1 to (Form1.Width div 12) do {îðãàíèçóåì öèêë îò åäèíèöû äî ÷èñëà ñòðîê, ïîìåùàþùèõñÿ íà ýêðàíå} begin k := i*LStr-1+Nbit; {âû÷èñëÿåì íîìåð â ìàññèâå mas ïîñëåäíåãî ýëåìåíòà ïðåäûäóùåé ñòðîêè} for j := 1 to LStr do {îðãàíèçóåì öèêë ïî âñåì ýëåìåíòàì ñòðîêè îò ïåðâîãî äî LStr} begin inc(k); {âû÷èñëÿåì íîìåð k ýëåìåíòà ìàññèâà mas, êîòîðûé äîëæåí áûòü îòîáðàæåí} if k>=Lmas then break; {åñëè î÷åðåäíîé íîìåð ýëåìåíòà ìàññèâà mas ïðåâûøàåò ëèáî ðàâåí äëèíå ìàññèâà Lmas, òî öèêë îòîáðàæåíèÿ áóäåò çàâåðøåí; äàííîå óñëîâèå âûïîëíÿåòñÿ ïðè âûâîäå íà ýêðàí íåïîëíîé ïîñëåäíåé ñòðîêè} if mas[k] = 0 then Buff.Canvas.TextOut(j*8, 12*i-4, '0') else Buff.Canvas.TextOut(j*8, 12*i-4, '1'); {îòîáðàæàåì k-é ýëåìåíò ìàññèâà íà êàíâå ôîðìû} end; end; Form1.Canvas.Draw(0, 0, Buff); {êîïèðóåì áèòîâóþ ìàòðèöó íà êàíâó ôîðìû} end; end; procedure TForm1.N4Click(Sender: TObject); var f: file of byte; {ôàéëîâàÿ ïåðåìåííàÿ äëÿ ðàáîòû ñ òèïèçèðîâàííûì ôàéëîì, ñîäåðæàùèì áàéòû} i, z: integer; {ïåðåìåííûå, èñïîëüçóåìûå êàê ñ÷åò÷èêè} d: byte; {ïåðåìåííàÿ, èñïîëüçóåìàÿ äëÿ ÷òåíèÿ áàéòà èç ôàéëà} begin if not OpenDialog1.Execute then exit;{åñëè ôàéë íå âûáðàí, òî ðàáîòà ïðîöåäóðû çàâåðøàåòñÿ} try {íà÷àëî áëîêà îáðàáîòêè èñêëþ÷èòåëüíîé ñèòóàöèè; äàæå â ñëó÷àå îøèáêè ïðè âûïîëíåíèè îïåðàòîðîâ ðàáîòû ñ ôàéëîì, áóäóò âûïîëíåíû îïåðàòîðû, ðàçìåùåííûå ïîñëå îïåðàòîðà finally, òî åñòü ôàéë f áóäåò çàêðûò} AssignFile(f, OpenDialog1.FileName); {ñ ôàéëîâîé ïåðåìåííîé f ñâÿçûâàåòñÿ ôàéë, âûáðàííûé ñ ïîìîùüþ êîìïîíåíòà OpenDialog1} Reset(f); {ôàéë f îòêðûâàåòñÿ äëÿ ÷òåíèÿ} {â ïàíåëè ñòàòóñà îòîáðàæàåì èìÿ îòêðûâàåìîãî ôàéëà} i := 0; {óñòàíàâëèâàåì â 0 çíà÷åíèå ñ÷åò÷èêà ñ÷èòàííûõ áèò} while not eof(f) do {âûïîëíÿåì öèêë ïîêà íå äîñòèãíóò êîíåö ôàéëà f} begin Read(f, d); {÷èòàåì èç ôàéëà f áàéò d} for z := 0 to 7 do {öèêë çàïèñè áèò áàéòà d â ìàññèâ mas} begin SetLength(mas, i+1); {óñòàíàâëèâàåì äëèíó ìàññèâà mas ðàâíîé íîìåðó ñ÷èòûâàåìîãî áèòà ïëþñ îäèí} mas[i] := (d shr z) and 1; {ïðè ðàçëè÷íûõ z ïîñëåäîâàòåëüíî ïðèñâàèâàåì î÷åðåäíîìó çíà÷åíèþ ìàññèâà çíà÷åíèå áèòà áàéòà d, ñíà÷àëà ìëàäøåãî áèòà, äàëåå âòîðîãî áèòà è òàê äî ñàìîãî ñòàðøåãî áèòà áàéòà d} inc(i); {óâåëè÷èâàåì íà îäèí ñ÷åò÷èê ñ÷èòàííûõ áèò} end; end; Lmas := i; {îáùåå ÷èñëî ñ÷èòàííûõ áèò} finally CloseFile(f); {çàêðûòèå ôàéëà f} end; if N5.Checked then Ris1 else Ris2; {â çàâèñèìîñòè îò âûáðàííîãî ðåæèìà îñóùåñòâëÿåòñÿ çàïóñê ïðîöåäóðû îòîáðàæåíèÿ â ãðàôè÷åñêîì âèäå Ris1 ëèáî â òåêñòîâîì Ris2; ïóíêò ìåíþ N5, ñîîòâåòñòâåííî, îòâå÷àåò çà âûáîð ãðàôè÷åñêîãî ðåæèìà, N6 - çà âûáîð òåêñòîâîãî ðåæèìà} end; initialization Buff := TBitmap.Create; Buff.Width := Screen.Width; Buff.Height := Screen.Height; finalization Buff.Free; end. |
| Автор | Сообщение |
|---|---|
|
Заголовок сообщения: List index out of bounds (0) и еще пара замечаний
|
|
|
|
Долгое время использовал бесплатную версию DBGridEh в своем проекте. Проект этот создан на D7. В принципе все устраивало, компонент стабильный, возможностей достаточно много, но… Не хватало самую малость. CellButtons — то что мне нужно сейчас. Установил оценочную версию EhLib.VCL 10.1 и началось… Вложение:
2. Кидаем датасет, добавляем колонки в грид, добавляем CellButtons. В первой у меня заполнен Glyph, Вторая DropDown, третья тоже Glyph но из ImageList. Вроде бы все хорошо, но как-то некрасиво. Вложение:
Делаем Uses XPMan. Теперь красиво, но, что стало с кнопками? Почему теперь не видно картинки на неактивных кнопках? Вложение:
Ну вот как покупать такое «изделие»? Ну и как пожелание: Вложение:
|
| Вернуться наверх |
|
|
EhLibSupport |
Заголовок сообщения: Re: List index out of bounds (0) и еще пара замечаний
|
|
|
Добрый день. Цитата: 1 На гриде без столбцов или с двумя созданными столбцами. Есть ли у вас возможность проверить, воспроизводится ли ошибка на других компьютерах, других ОС, других Формах (TForm)? Цитата: 2. Кидаем датасет, добавляем колонки в грид, добавляем CellButtons. В первой у меня заполнен Glyph, Вторая DropDown, третья тоже Glyph но из ImageList. Вроде бы все хорошо, но как-то некрасиво. Можете описать конкретнее, как должны отрисовываться кнопки чтобы выглядеть красиво? Цитата: Делаем Uses XPMan. Теперь красиво, но, что стало с кнопками? Почему теперь не видно картинки на неактивных кнопках? Можете прислать ваши файлы формы (dfm+pas) на support@ehlib.com ? Цитата: Есть гриды с высотой строки больше стандартной. а CellButtons в таких строках имеют стандартную высоту. Выглядит это не очень. Хотелось бы иметь возможность менять высоту этих кнопок в соответствии с высотой строк или произвольно, а также размещать эти кнопки в ряд не только горизонтально, но и вертикально, если высота строки это позволяет. К сожалению в текущей версии ручная высота кнопок и вертикальное размещение не поддерживаются. _________________ |
| Вернуться наверх |
|
|
edward_1 |
Заголовок сообщения: Re: List index out of bounds (0) и еще пара замечаний
|
|
|
В предыдущем посте я использовал Windows XP [Версия 5.1.2600], Delphi 7 Professional (Build 4.453), EhLib 10.1.022 Evaluation. Вложение:
DrawBackTime = edbtAlwaysEh Вложение:
В последнем случае наш битмап больше похож на маску, нежели на изображение. В старых версиях DBGridEh в EditButtons битмапы отображались корректно, их было хорошо видно: Вложение:
Хочу заметить, на данном этапе теста значение свойства HorzPlacement может быть любым. Вложение:
Ну и копирование — вставка грида вызывает ошибку, описанную в предыдущем посте. |
| Вернуться наверх |
|
|
edward_1 |
Заголовок сообщения: Re: List index out of bounds (0) и еще пара замечаний
|
|
|
Установил EhLib 10.1.023 Evaluation version. Ничего не изменилось. Все замеченные баги на месте. |
| Вернуться наверх |
|
|
aush |
Заголовок сообщения: Re: List index out of bounds (0) и еще пара замечаний
|
|
|
Оффтопик конечно, но в 2021 году стоит «закопать обоих стюардесс» (XP & Delphi7) |
| Вернуться наверх |
|
|
edward_1 |
Заголовок сообщения: Re: List index out of bounds (0) и еще пара замечаний
|
|
|
aush писал(а): Оффтопик конечно, но в 2021 году стоит «закопать обоих стюардесс» (XP & Delphi7) Это когда делать нечего, можно и закопать. А когда это проект в D7, в котором 150+ юнитов и форм, выполняющий свои задачи на 100% — закапывать тут нечего. Это не касается XP. |
| Вернуться наверх |
|
|
EhLibSupport |
Заголовок сообщения: Re: List index out of bounds (0) и еще пара замечаний
|
|
|
Добрый день. — — — Цитата: В последнем случае наш битмап больше похож на маску, нежели на изображение. В старых версиях DBGridEh в EditButtons битмапы отображались корректно, их было хорошо видно: Можете написать, в какой версии EditButton точно работали? _________________ |
| Вернуться наверх |
|
|
edward_1 |
Заголовок сообщения: Re: List index out of bounds (0) и еще пара замечаний
|
|
|
EhLibSupport писал(а): Ошибку “с многочисленным сообщением «List index out of bounds (0)»” так воспроизвести и не удалось. Странно. При копировании — вставке грида мне наоборот, не удается избежать данной ошибки. Даже если грид пустой. edward_1 писал(а): Можете написать, в какой версии EditButton точно работали? В версии 5.2 кнопки отображались так: Вложение:
edward_1 писал(а): Для отображения картинки в текущей версии можно установить EditButton. AutoFade = False Если установить EditButton. AutoFade = False, получаем изображение всех кнопок одинаковым, без учета активной/неактивной кнопок: Вложение:
Если же использовать например PngImageList, то все нормально: Вложение:
Выходит, добавив новые возможности отображения кнопок с использованием ImageList, старые методы поломали. |
| Вернуться наверх |
|

помогите поправить код на Delphi
, вылетает с ошибкой elisterror list index out of bounds (0)
- Подписаться на тему
- Сообщить другу
- Скачать/распечатать тему
|
|
|
|
Здравствуйте знатоки. Задали задачку по мат. моду, нужно реализовать программу которая моделирует движение космического корабля относительно земли. В принципе писать можно на чем угодно, в основном пишут на маткаде и матлабе, я выбрал на делфи. Набросал код, но вылетает с ошибкой, блин хоть убей не пойму где косяк, поправьте пожалуйста. Прога запускается, но когда нажимаешь на кнопку для расчета вылетает с ошибкой elisterror list index out of bounds (0) код ниже
procedure TForm1.Button1Click(Sender: TObject); var //——————————————— x,y,z,time,vx,vy,vz,rad_v:array[0..5000] of real ; TT,vs,v0,t,dt:Extended; h,h2,r,MM,G,m:Extended; i,j,k:integer; begin Chart1.Series[0].Clear; //Chart1.Series[1].Clear; //Chart1.Series[2].Clear; if edit1.Text =» then ShowMessage(‘Введите скорость станции!’) else Begin if edit2.Text =» then ShowMessage(‘Введите скорость аппарата!’) else Begin h:=strtofloat(Edit1.Text); v0:=strtofloat(Edit2.Text); G:=6.67e-11;//—-гравит-я пост MM:=6e+24;//—масса Земли m:=strtofloat(Edit3.Text); //масса аппарата h2:=6400000;//радиус Земли(м) h:=h*h2; R:=h+h2; vs:=sqrt(G*MM/R);//скорость t:=0; //——-время dt:=10;//——шаг по времени TT:=(2*Pi*(r+h))/vs; //——-период станции k:=1000; //———————————— t:=dt; i:=0; time[0]:=0; //—Начальные условия x[0]:=R; y[0]:=0; z[0]:=0; vx[0]:=0; vy[0]:=vs; vz[0]:=v0; //rad_v[0]:=sqrt(x[0]*x[0]+y[0]*y[0]+z[0]*z[0]); //showmessage(floattostr(R)); //showmessage(floattostr(rad_v[0])); while (i<5000) do begin rad_v[i]:=sqrt(x[i]*x[i]+y[i]*y[i]+z[i]*z[i]); if rad_v[i]=0 then begin showmessage(‘радиус вектор=0’); showmessage(floattostr(i)); break; end; vx[i+1]:=vx[i]-(G*MM*x[i]*dt)/(rad_v[i]*rad_v[i]*rad_v[i]*m); x[i+1]:=x[i]+dt*vx[i+1]; vy[i+1]:=vy[i]-(G*MM*y[i]*dt)/(rad_v[i]*rad_v[i]*rad_v[i]*m); y[i+1]:=y[i]+dt*vy[i+1]; vz[i+1]:=vz[i]-(G*MM*z[i]*dt)/(rad_v[i]*rad_v[i]*rad_v[i]*m); z[i+1]:=z[i]+dt*vz[i+1]; i:=i+1; // t:=t+dt; if i<>0 then begin t:=t+dt; time[i]:=t; end; end; // showmessage(floattostr(rad_v[0])); //—————график————————- Chart1.Series[0].XValues.Order:=loNONE; for j:=0 to i-1 do begin Chart1.Series[0].AddXY(time[j],rad_v[j]); end; //————————————— |
|
Павел Калугин |
|
|
Вылеет за границы списка. Список тут Chart1.Series. Возможно он пуст? То есть в нем отсутствует значение с индексом 0 Добавлено 26.01.10, 12:50 |
|
mnemonik |
|
|
ммм, что то не понял, напишите пожалуйста подробнее. Сообщение отредактировано: mnemonik — 26.01.10, 12:55 |
ttiger |
|
|
Moderator
Рейтинг (ф): 166 |
Цитата mnemonik @ 26.01.10, 12:42 когда нажимаешь на кнопку для расчета вылетает с ошибкой elisterror list index out of bounds (0) код ниже Кнопка расчета — Button1? Наведи курсор на строку
Chart1.Series[0].Clear;
и нажми F5 (появится брекпойнт). Скорее всего, ошибка в первой строчке. Ты не задал серии в чарте. |
ttiger |
|
|
Moderator
Рейтинг (ф): 166 |
Вопрос решен или нет? |
0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
0 пользователей:
- Предыдущая тема
- ПОМОЩЬ СТУДЕНТАМ
- Следующая тема
[ Script execution time: 0,1399 ] [ 15 queries used ] [ Generated: 28.01.23, 18:02 GMT ]
Данный текст является ознакомительным фрагментом.
Читайте также
Пополнение индекса
Пополнение индекса
Как говорилось выше, по умолчанию проиндексированными являются только личные папки пользователей. Если попытаться найти файл в неиндексированной папке, появляется всплывающее предложение добавить каталог в список индексируемых. Однако вы можете
Создание индексов с помощью команды CREATE INDEX
Создание индексов с помощью команды CREATE INDEX
Помимо создания индексов в процессе формирования таблицы (с помощью предложения CONSTRAINT), можно также создавать индексы уже после того, как таблица сформирована (с помощью предложения CREATE INDEX). Это полезно в тех случаях, когда
Изменение индекса
Изменение индекса
Активация/деактивация
Оператор ALTER INDEX используется для переключения состояния индекса из активного в неактивное и наоборот. Он может быть применен для отключения индекса перед добавлением или изменением большого пакета строк и устранения при этом
Удаление индекса
Удаление индекса
Оператор DROP INDEX удаляет созданный пользователем индекс из базы данных.Используйте DROP INDEX также в случае необходимости изменения структуры индекса: добавление, удаление сегментов, изменение порядка сегментов или изменение порядка сортировки. Вначале
Улучшение селективности индекса
Улучшение селективности индекса
Вообще говоря, селективность (избирательность) индекса — это оценочное количество строк, которые могут быть выбраны при поиске по каждому значению индекса. Уникальный индекс имеет максимально возможную селективность, потому что он не
13-я КОМНАТА: О прикладном значении арт-авангарда
13-я КОМНАТА: О прикладном значении арт-авангарда
Автор: Леонид Левкович-МаслюкВ сегодняшнем номере вы прочитаете о компьютерном мультфильме «Кошечка», на много лет обогнавшем свое время изощренностью алгоритмов. По касательной к этой теме — взаимоотношения
Ошибка 0x00000037: ошибка FDD
Ошибка 0x00000037: ошибка FDD
Ошибка дисковода для гибких дисков. Он у вас еще
Ошибка 0x0000003E: ошибка асимметричности
Ошибка 0x0000003E: ошибка асимметричности
Ошибка асимметричности мультипроцессорной системы. У вас два процессора? Тогда проследите, чтобы они работали на одной частоте. Например, вы могли установить один процессор, который работает на частоте 1,6 ГГц, а второй – 1,8 ГГц. Вот вам
Ошибка 0x00000051: ошибка реестра
Ошибка 0x00000051: ошибка реестра
Возможно, файлы реестра повреждены. Обычно данную проблему может помочь решить восстановление системы, после которого нужно произвести проверку жесткого диска на наличие «битых»
Ошибка 0x00000075: ошибка сохранения реестра
Ошибка 0x00000075: ошибка сохранения реестра
Ошибка сохранения реестра, а именно – нет места для сохранения реестра. Пора покупать новый жесткий
Ошибка 0x0000009C:ошибка при проверке «железа»
Ошибка 0x0000009C:ошибка при проверке «железа»
Критическая ошибка при проверке оборудования. Попробуйте переустановить
Ошибка 0x000000C4: ошибка в драйвере
Ошибка 0x000000C4: ошибка в драйвере
При проверке драйверов была обнаружена фатальная ошибка в одном из драйверов. Поможет переустановка
Topic: List Index (0) out of bounds (Read 26574 times)
I get this when I try to add data to multiple charts …
I have 3 charts. If I add data to only one of them, everything’s ok. If I add data to both of them, it cracks…
List Index (0) out of boundsI am not adding data in the same time. A thread is doing the Data Acquisition if I can call it like that, and adds it to charts based on some parameters. This means that the two graphs are not updated at the same time.
if parameter = 1 thenSomething like that. Any ideas why it is causing that error?
list1.Add(x,y)
else if Parameter = 2 then
List2.Add(x,y);

Logged
Impossible to identify your problem with this little information. Just a few ideas:
Use the debugger to identify the faulty «list». This error usually occurs when you access the index of a nondefined list item. In your case, maybe the chart source does not contain any data yet, but you are reading the first item (index 0)?
Also, since you seem to be working with threads, are you sure that you follow the rules with thread synchronization etc.?

Logged
Hello,
Happens to me too.
I still have not been solved at all, because I get the error randomly when using charts.
But I think it has something to do with the .clear method of the series.
Do you use something in your code as «LineSeries1.Clear;»?
If so, try changing it to «LineSeries1.Active: = false;» and «LineSeries1.Active: = true;»
I use Lazarus v1.1 and windows.
A greeting. And sorry for not speaking English.
——————————————-
Traducido por google. Original:
Hola,
A mi también me pasa.
Todavia no lo he podido solucionar del todo, pues me sale el error al azar al usar charts.
Pero creo que tiene algo que ver con el método .clear de la serie.
¿Usas algo en tu código como «LineSeries1.Clear; » ?
Si es así, intenta cambiarlo por «LineSeries1.Active:=false;» y «LineSeries1.Active:=true;»
Un saludo.
Y perdón por no saber inglés.

Logged
@wp I am using the Debugger but it does not show where the error occurs from. The Call stack is all weird. Still, if you saying that I’m trying to access values that are not assigned yet, I do have an idea now…
I use a ring buffer to update the chart. I get the values from some other thread, and I store them into the buffer. I get multiple variables in an array of bytes, work with them, write them into the ring buffer and after that, I clear the graph and write the new buffer in the graph. I do
List1.Clear;Where RingBuffer is
for i := 0 to RingBuffer.Size - 1 do
List1.Add(CalculatedValue, RingBuffer.Data[i])
type RingBuffer = RecordWhat could be the problem? The graph tries to update itself right after the Clear and I try to write in the same time or what?
Size : integer;
WritePoint : integer;
ReadPoint : Integer;
Data : Array of Integer;
end;
I use the ring Buffer because I want the chart to have the values of last X datas received from the other thread so, I write 5 datas into the ring buffer, update the chart and when the next data arrives, the oldest data in the Buffer is being overwritten…
@Arthurus, yes I am. Making it inactive will not help me. I need to clear it.
//Threads Sync and critical sections are used. I took this in consideration… It does not seem to be that…
« Last Edit: September 22, 2013, 04:50:38 pm by hac3ru »

Logged
Without your sources it is difficult to help. Here’s what I would do:
- Instead of using a chart I’d write the ring buffer to a file for a test. If this prodecues the error the bug could be in the ring buffer logics. Is its memory allocated correctly? Are the data indices out of range?
- For a test, try to remove the thread, create dummy data maybe by means of a button click and treat them as if they would come from the thread. If this works the error should be in the thread logics, synchronization etc.
- All these tests could give you an idea how to condense your program into a little demo project which shows the error and which you can upload here.

Logged
hac3ru:
The error is: (Because this does not work well. I think it must be a bug…)
List1.Clear;
What is List1? TLineSeries? or TOpenHighLowCloseSeries? or…..
Replace it with one like this:
for i:=0 to Chart1.SeriesCount-1 do
begin
if Chart1.Series[i] is TLineSeries then TLineSeries(Chart1.Series[i]).Clear;
if Chart1.Series[i] is TOpenHighLowCloseSeries then TOpenHighLowCloseSeries(Chart1.Series[i]).Clear;
end;
A greeting.

Logged
What is List1? TLineSeries? or TOpenHighLowCloseSeries? or…..
From the context I’d guess that it is a TListChartSource.
Because this does not work well. I think it must be a bug…
Could you be more specific? In my own experience with many charts, TListChartSource is working fine.
Replace it with one like this:
if Chart1.Series[ i] is TLineSeries then TLineSeries(Chart1.Series).Clear;
if Chart1.Series[ i] is TOpenHighLowCloseSeries then TOpenHighLowCloseSeries(Chart1.Series).Clear;
No, this is useless. «Clear» is not a virtual method, it is implemented by their ancestor TChartSeries, and in every case it just clears the internal ListSource (i.e. is doing what you are claiming above to be faulty).
« Last Edit: September 23, 2013, 12:27:59 am by wp »

Logged
hac3ru:
The error is: (Because this does not work well. I think it must be a bug…)List1.Clear;
What is List1? TLineSeries? or TOpenHighLowCloseSeries? or…..Replace it with one like this:
for i:=0 to Chart1.SeriesCount-1 do
begin
if Chart1.Series[i] is TLineSeries then TLineSeries(Chart1.Series[i]).Clear;
if Chart1.Series[i] is TOpenHighLowCloseSeries then TOpenHighLowCloseSeries(Chart1.Series[i]).Clear;
end;
A greeting.
List1 is a ListChartSource…
Ideas?

Logged
In my program of charts I’ve spent like 2 months trying to discover the cause of this error «List index (0) out of bounds», very hard to detect.
And since I have already changed that code I have not seen that error message.
Use Win & Firebird & Lazarus-1.1-40379-fpc-2.6.1-20130224-win32
@hac3ru: I do not use ListChartSource. But I am convinced that it has something to do with .Clear
Perhaps another thing, but in my case, I’ve solved so… and now going well.
A greeting.
———————————————
Traslate by bing. ORIGINAL:
En mi programa de charts me he pasado como unos 2 meses intentando descubrir la causa de ese error «List index(0) out of bounds», muy dificil de detectar.
Y desde que he cambiado ese código ya no he vuelto a ver ese mensaje de error.
@hac3ru: No uso ListChartSource. Pero estoy convencido de que tiene algo que ver con .Clear
Quizá sea otra cosa, pero en mi caso, yo lo he solucionado así… y por ahora me va bien.

Logged
I do not use ListChartSource.
Even if you don’t expicitly use a ListChartSource you do use it nevertheless because the data that you «Add» to the series go into a ListChartSource.
But I am convinced that it has something to do with .Clear
You are probably accessing one of the data points after the Clear. Something like
x := Chart1LineSeries1.ListSource.Item[0]^.x;There are some other methods of the ListChartSource that do that, like FormatItem or FormatItemXYText. After Clear, there are no more data points, Item[0] does not exist any more, and you will get the «List index (0) out of bounds» error. Of course, you don’t call this intenionally, but maybe one your event handlers does it and gets called after the Clear.
When you, as you mentioned in one of the upper postings, hide the series instead of clearing it, of course, the error will not appear since the data points are still there. I am pretty sure that you did not solve your original issue this way, let’s hope that it does not come back to you.

Logged
Okay so …. How can I fix it? How can I tell who causes the error? 

Logged

Logged
Compile Lazarus with debug information on (Tools / Configure «Build Lazarus» / Profile to build: Debug IDE). Then Lazarus should stop at the source line, maybe in one of the TAChart units, which caused the crash. From that you can investigate backwards, for example by looking at the stack trace to see from which procedure the error line was called. Without knowing your code I can’t be more specific…

Logged
I’m back to change the code to cause the error
With the debugger, I get this message:
http://img845.imageshack.us/img845/1876/pyi2.jpg
And does not lead to any line of code: the Lazarus crashes:
http://img194.imageshack.us/img194/5121/zjlw.jpg
(My computer is a Core2Duo with 4Gb ram)
CODE:
Click in DbGrid: See where it says HERE
procedure TForm1.DBGrid1CellClick(Column: TColumn);
begin
Ref_ID:=SQLQuery1REF.AsInteger;
BtnHoyClick(BtnHoy);
SQLQuery2.Close;
SQLQuery2.SQL.Text:='select * from tabla_val where ref=:REFER order by fecha;';
SQLQuery2.ParamByName('REFER').AsInteger:=Ref_ID;
SQLQuery2.Open;
SQLQuery2.Last;
ultPreu:=SQLQuery2CIERRE.AsFloat; // ultPreu para EstudioMedias.MediaP
if SQLQuery1CIERRE.AsFloat>SQLQuery1AYER.AsFloat then Label4.Font.Color:=clBlue
else if SQLQuery1CIERRE.AsFloat=SQLQuery1AYER.AsFloat then Label4.Font.Color:=clBlack
else Label4.Font.Color:=clRed;
Label4.Caption:='C='+FormatFloat('##0.###',SQLQuery1CIERRE.AsFloat)+' ('+
Format('%7.3n', [SQLQuery1CIERRE.AsFloat-SQLQuery1AYER.AsFloat]) + ') '+
Format('%4.2n',[(SQLQuery1CIERRE.AsFloat-SQLQuery1AYER.AsFloat)/SQLQuery1AYER.AsFloat*100])+'%'+
' H='+FormatFloat('##0.###',SQLQuery1HIGH.AsFloat)+' L='+FormatFloat('##0.###',SQLQuery1LOW.AsFloat)+
' ' + SQLQuery1FECHA.AsString ;
SQLQuery2.MoveBy(NumSesiones);
LimpiaChart; // <----------------------------------------------- HERE --------------------------------------------------------------
Chart1.ZoomFull;
if SQLQuery1ENCARTERA.AsString='S' then
begin
chart1.BackColor:=clTeal;
if not chart1.Visible=true then Panel6.Visible:=true;
end
else begin
chart1.BackColor:=ColorFondoGrafico;//clSilver;//clBlack;
Panel6.Visible:=false;
end;
if (MediaDeTabla=True) and (SQLQuery8OpcionesUSARMEDPART.AsString='S') then EditMP.Text:=IntToStr(SQLQuery1MEDIA.AsInteger);
case Estudio of
1:EstudioCV.pintaChart;
2:EstudioMedias.MediaP(StrToInt(EditMP.Text)); // <---------------------------------------- HERE ----------------------------------
end;
LabelHi.Caption:='';LabelCi.Caption:='';LabelLo.Caption:='';
LabelHi1.Caption:='';LabelCi1.Caption:='';LabelLo1.Caption:='';
MediaDeTabla:=True;
end;
Clean the Chart:
procedure TForm1.LimpiaChart;
var i:integer;
begin
{
for i:=0 to Chart1.SeriesCount-1 do
begin
if Chart1.Series[i] is TLineSeries then TLineSeries(Chart1.Series[i]).Clear;
if Chart1.Series[i] is TOpenHighLowCloseSeries then TOpenHighLowCloseSeries(Chart1.Series[i]).Clear;
end;
}
Chart1hlc.Clear;
LineS1.Clear;
LineMediaP7Max.Clear;
LineMediaP6Max.Clear;
LineMediaP5Max.Clear;
LineMediaP4Max.Clear;
LineMediaP3Max.Clear;
LineMediaP2Max.Clear;
LineMediaP1Max.Clear;
LineMediaP1.Clear;
LineMediaP1Min.Clear;
LineMediaP2Min.Clear;
LineMediaP3Min.Clear;
LineMediaP4Min.Clear;
LineMediaP5Min.Clear;
LineMediaP6Min.Clear;
LineMediaP7Min.Clear;
end;
With .Active:=false; the program behaves better than .Clear;
« Last Edit: September 24, 2013, 10:55:51 pm by Arthurus »

Logged
Thanks for showing some code. But it’s still difficult to see the details. Could you write a simplified version of your application which contains the essential parts to show the bug? You could skip database access in the first try and just add random values to the series. Upload this project here, I can try to have a look at it (no guarantee, though…)
When you step into «LimpiaChart» the «Clear» of which series causes the crash?
Temporarily remove Chart1.ZoomFull in «DBGridCellClick»? Do you zoom somewhere in your code? Deactivate this (and other ChartTools) for debugging, it may have a life of its own.
Which series types are used? Do they get data from an external chart source? Do you use a DBChartSource?
You don’t seem to put your code into methods of TForm1, but call non-object procedures instead. Could it be that you have a second instance of TForm1 which you intend to call, but since Form1 is hardcoded into your procedures they use Form1 instead of the other form?

Logged



