Ad

Index Out Of Range (-1) When I Click On Any Item In The TListBox

- 1 answer

The TListBox called lboMtrlList is populated with records from the database. The data displays properly when I run the application. When I click on any item in the list, shows the error:

Index out of range (-1)

despite the list not being empty.

Here's the code for populating the lboMtrlList:

procedure TfrmMakeQuote.FormCreate(Sender: TObject);
 begin
  con := TFDConnection.Create(nil);
  query := TFDQuery.Create(con);
  con.LoginPrompt := false;
  con.Open('DriverID=SQLite;Database=C:\Users\katiee\Documents\Embarcadero\Studio\Projects\ProgramDatabase;');
  query.Connection := con;
  performQuery;

  query.SQL.Text :=
  'SELECT [Material Description] FROM MtrlDatabase ORDER BY MtrlID';
 try
  query.Open;
  lboMtrlList.Items.Clear;
  while not query.EOF do
   begin
    lboMtrlList.Items.Add(query.Fields[0].AsString);
    query.Next;
   end;
  finally
   query.Close;
 end;
 //ledtDesc.Height :=  81;
 //ledtNotes.Height :=  51;
 end;

I want to be able to double click on an item in the lboMtrlList and move it to another TListBox called lboSelectedMtrl. Here's the code:

procedure TfrmMakeQuote.lboMtrlListDblClick(Sender: TObject);
 begin
  lboMtrlList.Items.Add(lboSelectedMtrl.Items.Strings[lboSelectedMtrl.ItemIndex]);
 end;
Ad

Answer

I want to be able to double click on an item in the lboMtrlList and move it to another TListBox called lboSelectedMtrl.

Your code is doing the opposite of that. It is trying to move an item from lboSelectedMtrl to lboMtrlList. You are getting the bounds error because there is no item selected in lboSelectedMtrl (lboSelectedMtrl.ItemIndex is -1).

Swap the ListBox variables, and add some error checking:

procedure TfrmMakeQuote.lboMtrlListDblClick(Sender: TObject);
var
  Idx: Integer;
begin
  Idx := lboMtrlList.ItemIndex;
  if Idx <> -1 then
    lboSelectedMtrl.Items.Add(lboMtrlList.Items.Strings[Idx]);
end;
Ad
source: stackoverflow.com
Ad