delphilistboxcenteringtlistbox

How to vertically center TListBox item?


So I want to vertically center the TListBox (not TListView) item.

I can use TopIndex property, but how do I do the whole thing.

If there are fewer items so the scroll bar doesn't appear, then centering is not required, only selection of default item will do just fine.

Something like this:

Vertically Centered TListBox


Solution

  • enter image description here

    //IF YOU WANT TO SELECT THE CENTER ITEM 
    procedure TForm2.Center;
      var VisibleItems : Integer;
    begin
      VisibleItems := ListBox1.ClientHeight div  ListBox1.ItemHeight;
      ListBox1.TopIndex := Trunc((ListBox1.Items.Count / 2) - (VisibleItems / 2));
      if ListBox1.Items.Count > VisibleItems then
        ListBox1.Selected[ListBox1.TopIndex + (VisibleItems div 2)] := True
      else
        ListBox1.Selected[ListBox1.Items.Count div 2] := True;
    end;
    
    
    
    //IF YOU WANT TO CENTER A ITEM
    procedure TForm2.Center(Index : Integer);
      var VisibleItems : Integer;
    begin
      VisibleItems := ListBox1.ClientHeight div ListBox1.ItemHeight;
      if Index > VisibleItems then
        ListBox1.TopIndex :=  Index - (VisibleItems div 2);
    end;