auto extend a listbox

boycoder
boycoder used Ask the Experts™
on
Hi i have a small list box, how can i extend the size of the hieght based on entries?

so when 3 items are added for example its the exact size of the 3, same for 2 and all the way up to 10, then it starts to show the scroller?

Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Presumably the number of items is changed at runtime. I don't know how or when you do this, but after you change the number of items in the listbox's itemlist, check the number of items and ajust the height of the listbox.

Sample program: form, listbox1, botton1, botton2,

Just two onclick events



procedure TForm1.Button1Click(Sender: TObject);
begin
  listbox1.Items.Add('test');
  if listbox1.Items.Count > 10 then
    listbox1.Height := 10 * listbox1.ItemHeight + 5
  else
    listbox1.Height := listbox1.Items.Count * listbox1.ItemHeight + 5;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  listbox1.Items.Delete(1);
  if listbox1.Items.Count > 10 then
    listbox1.Height := 10 * listbox1.ItemHeight + 5
  else
    listbox1.Height := listbox1.Items.Count * listbox1.ItemHeight + 5;
end;

Simple but effective
Ferruccio AccalaiSenior developer, analyst and customer assistance

Commented:
You cal also use this approach.
Set the ListBox style to lbOwnerDrawFixed

then

procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState);
begin
  with ListBox1.Canvas do
  begin
    ListBox1.Canvas.FillRect(Rect);
    TextOut(Rect.Left, Rect.Top, ListBox1.Items[Index]);
  end;
  ListBox1.Height := ListBox1.ItemHeight*ListBox1.Items.Count;
end;
hi

Try this codings

  ListBox1.ItemHeight:= 20;
  ListBox1.Items.Add('boycoder');
  ListBox1.Height:=  ListBox1.Height + ListBox1.ItemHeight;
  ListBox1.Refresh;

surely it will work....
by
kumaresan
uResizelistbox.dfm
uResizelistbox.pas
Project1.exe
Project1.dpr

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial