Link to home
Create AccountLog in
Avatar of boycoder
boycoder

asked on

auto extend a listbox

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
Avatar of Thomas_Roes
Thomas_Roes

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
Avatar of Ferruccio Accalai
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;
ASKER CERTIFIED SOLUTION
Avatar of kumaresan2011
kumaresan2011
Flag of India image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer