Also, have you considered using a check list box? It may be easier for the user to use checkboxes for each item rather than holding Ctrl and selecting, or however you have it made.
In situations where I want a list displayed, but need to reference each item to some other object somewhere, I make use of the list items' objects. I also have a class which I uniquely store in that list. Most commonly, I use a common class of mine "TListVal" with just two simple properties: Caption and ID. Caption meaning what to display in the list, and ID meaning the ID in the database. That way, when the user selects one of the items, I can read this object and get the ID...
Code:
type
TListVal = class(TObject)
private
fID: Integer;
fCaption: String;
fDescription: String;
fSelected: Bool;
public
constructor Create(ID: Integer);
property ID: Integer read fID write fID;
property Caption: String read fCaption write fCaption;
property Description: String read fDescription write fDescription;
property Selected: Bool read fSelected write fSelected;
end;
implementation
constructor TListVal.Create(ID: Integer);
begin
fID:= ID;
end;
Refreshing the items in the list...
Code:
procedure TForm1.LoadList;
var
Q: TADOQuery;
X: Integer;
V: TListVal;
begin
//First clear the items from the list, if any
for X:= 0 to ListBox1.Items.Count - 1 do
TListVal(ListBox1.Items.Objects[X]).Free; //Make sure any existing items are free'd, also upon app termination
ListBox1.Items.Clear;
//And fetch the data from the database
Q:= TADOQuery.Create(nil);
try
Q.Connection:= Connection;
Q.SQL.Text:= 'select * from MyTable';
Q.Open;
if not Q.IsEmpty then begin
Q.First;
X:= 0;
//Loop through the results
while not Q.Eof do begin
V:= TListVal.Create(Q.FieldByName('ID').AsInteger);
try
V.Caption:= Q.FieldByName('Caption').AsString;
V.Description:= Q.FieldByName('Description').AsString;
V.Selected:= Q.FieldByName('Selected').AsBoolean;
finally
Inc(X); //Just in case you need to use X for anything, not used in this example though
ListBox1.Items.AddObject(V.Caption, V);
Q.Next;
end;
end;
//Now loop back through and select them accordingly
for X:= 0 to ListBox1.Items.Count - 1 do begin
V:= TListVal(ListBox1.Items.Objects[X]);
ListBox1.Selected[X]:= V.Selected;
end;
end;
Q.Close;
finally
Q.Free;
end;
end;
Now, at any given time, you just get the object of the currently selected item and you automatically have its ID along with it, as well as a property specifying whether or not it's selected in the database (regardless of current user's selection). Of course it would need a lot of tweaking in your case, I'm not even sure if this is something you'll need, but it's another option to throw out there while we're on the topic of list items.
PS - All this above code was written 100% in the website, and has not even been tested in Delphi, so don't be surprised if there's a bug hidden somewhere in what I posted.
JD Solutions