Difference between revisions of "TListBox"

From Lazarus wiki
Jump to navigationJump to search
m (added link to tutorial)
 
(6 intermediate revisions by 4 users not shown)
Line 1: Line 1:
 
{{TListBox}}
 
{{TListBox}}
A '''TListBox''' [[image:tlistbox.png]] is a component that provides a scrollable list of (short) strings where user is to select one. It is available from the [[Standard tab]] of the [[Component Palette]].
 
  
[[image:Comp_Standard_TListBox.png]]
+
A '''TListBox''' [[image:tlistbox.png]] is a component that shows a (scrollable) list of (short) strings where user is to select one. It is available from the [[Standard tab]] of the [[Component Palette]].
  
In the ListBox, the stored [[String|strings]] are stored in the property ''Items'', that is of type TStrings. Thus you can assign or remove strings in the ListBox, as in a [[TStringList-TStrings Tutorial|TStringList]] or its parent [[TStringList-TStrings Tutorial|TStrings]].
+
In the TListBox, the stored [[String|strings]] are stored in the property ''Items'', that is of type [[TStrings]]. Thus you can assign or remove strings in the ListBox, as in a [[TStringList]] or its parent [[TStringList-TStrings Tutorial|TStrings]].
  
Here are a few examples of how to use a ListBox ''ListBox1'' on a form ''Form1'':
+
Here are a few examples of how to use a TListBox ''ListBox1'' on a form ''Form1'':
  
===Fill ListBox===
+
==Fill ListBox==
====by the Object Inspector====
+
===by the Object Inspector===
 
* Select the ListBox on your form with one click.
 
* Select the ListBox on your form with one click.
 
* Go in the Object Inspector in the Properties tab on the property ''Items''.
 
* Go in the Object Inspector in the Properties tab on the property ''Items''.
Line 15: Line 14:
 
* Enter your text and confirm your work with ''OK''.
 
* Enter your text and confirm your work with ''OK''.
  
====by code in button click====
+
===by code in button click===
 
Add your form a [[TButton]] with the name ''btnFill'' and caption ''fill ListBox''. In the event handler ''OnClick'' of the button, you write the following code:
 
Add your form a [[TButton]] with the name ''btnFill'' and caption ''fill ListBox''. In the event handler ''OnClick'' of the button, you write the following code:
<source>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.btnFillClick(Sender: TObject);
 
procedure TForm1.btnFillClick(Sender: TObject);
 
begin
 
begin
Line 26: Line 25:
 
   ListBox1.Items.Add('Even a random number '+IntToStr(Random(100)));
 
   ListBox1.Items.Add('Even a random number '+IntToStr(Random(100)));
 
end;
 
end;
</source>
+
</syntaxhighlight>
 
 
====Assignment of a StringList====
 
  
 +
==Assignment of a StringList==
 
Add your form a [[TButton]] with the name ''btnFill'' and caption ''fill ListBox''. In the event handler ''OnClick'' of the button, you write the following code:
 
Add your form a [[TButton]] with the name ''btnFill'' and caption ''fill ListBox''. In the event handler ''OnClick'' of the button, you write the following code:
<source>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.btnFillClick(Sender: TObject);
 
procedure TForm1.btnFillClick(Sender: TObject);
 
var
 
var
Line 44: Line 42:
 
   myStringList.Free;                              //Free my StringList in memory  
 
   myStringList.Free;                              //Free my StringList in memory  
 
end;
 
end;
</source>
+
</syntaxhighlight>
 
 
===Add string===
 
  
 +
==Add string==
 
* Extend the example [[TListBox#by code in button click|Fill ListBox by code in button click]] to a [[TEdit]] and a [[TButton]] with the name ''btnAdd'' and caption ''add string''. Change of ''Edit1'' the property ''Text'' to "" - empty string.
 
* Extend the example [[TListBox#by code in button click|Fill ListBox by code in button click]] to a [[TEdit]] and a [[TButton]] with the name ''btnAdd'' and caption ''add string''. Change of ''Edit1'' the property ''Text'' to "" - empty string.
 
* In the event handler ''OnClick'' of the button, you write the following code:
 
* In the event handler ''OnClick'' of the button, you write the following code:
<source>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.btnAddClick(Sender: TObject);
 
procedure TForm1.btnAddClick(Sender: TObject);
 
begin
 
begin
Line 56: Line 53:
 
   Edit1.Text:='';
 
   Edit1.Text:='';
 
end;  
 
end;  
</source>
+
</syntaxhighlight>
 
 
===Delete string===
 
  
 +
==Delete string==
 
By default is set that you can select only one row in your list box. Do you want to select several of the lines in your ListBox, you would have the property ''MultiSelect'' to make ''True''.
 
By default is set that you can select only one row in your list box. Do you want to select several of the lines in your ListBox, you would have the property ''MultiSelect'' to make ''True''.
  
====Delete string at ItemIndex====
+
===at ItemIndex===
  
 
* Extend the example [[TListBox#Add string|Add string]] to a [[TButton]] with the name "btnDel" and caption "delete string".
 
* Extend the example [[TListBox#Add string|Add string]] to a [[TButton]] with the name "btnDel" and caption "delete string".
 
* In the event handler ''OnClick'' of the button, you write the following code:
 
* In the event handler ''OnClick'' of the button, you write the following code:
<source>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.btnDelClick(Sender: TObject);
 
procedure TForm1.btnDelClick(Sender: TObject);
 
begin
 
begin
Line 72: Line 68:
 
     ListBox1.Items.Delete(ListBox1.ItemIndex);
 
     ListBox1.Items.Delete(ListBox1.ItemIndex);
 
end;  
 
end;  
</source>
+
</syntaxhighlight>
 
 
====Delete all selected strings====
 
  
 +
===all selected strings===
 
* Extend the example [[TListBox#Add string|Add string]] to a [[TButton]] with the name "btnDel" and caption "delete string".
 
* Extend the example [[TListBox#Add string|Add string]] to a [[TButton]] with the name "btnDel" and caption "delete string".
 
* In the event handler ''OnClick'' of the button, you write the following code:
 
* In the event handler ''OnClick'' of the button, you write the following code:
<source>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.btnDelClick(Sender: TObject);
 
procedure TForm1.btnDelClick(Sender: TObject);
 
var
 
var
Line 88: Line 83:
 
         ListBox1.Items.Delete(i);              //...delete the item (String)
 
         ListBox1.Items.Delete(i);              //...delete the item (String)
 
end;
 
end;
</source>
+
</syntaxhighlight>
 
 
===Owner-drawn ListBox===
 
  
 +
==Owner-drawn ListBox==
 
In general, it is advantageous to let the ListBox follow the  [http://en.wikipedia.org/wiki/Skin_%28computing%29 theme] set by the user. In some cases (for example, to program a game with a colorful surface), you can deviate from this standard and draw the control according to your own choice. You can try this now:
 
In general, it is advantageous to let the ListBox follow the  [http://en.wikipedia.org/wiki/Skin_%28computing%29 theme] set by the user. In some cases (for example, to program a game with a colorful surface), you can deviate from this standard and draw the control according to your own choice. You can try this now:
 
 
* You can modify the previous sample or create a new application with a TListBox ''ListBox1''.
 
* You can modify the previous sample or create a new application with a TListBox ''ListBox1''.
 
* In the Object Inspector, change ''ListBox1'' property ''Style'' to ''lbOwnerDrawFixed''.
 
* In the Object Inspector, change ''ListBox1'' property ''Style'' to ''lbOwnerDrawFixed''.
 
* With the Object Inspector, tab events, create the event handler for the event ''OnDrawItem'', by clicking on the button [...].
 
* With the Object Inspector, tab events, create the event handler for the event ''OnDrawItem'', by clicking on the button [...].
 
* You add the following code to the handler:
 
* You add the following code to the handler:
<source>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer;
 
procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer;
 
   ARect: TRect; State: TOwnerDrawState);
 
   ARect: TRect; State: TOwnerDrawState);
Line 114: Line 107:
 
   ListBox1.Canvas.TextRect(ARect, 2, ARect.Top+2, ListBox1.Items[Index]);  //Draw Itemtext
 
   ListBox1.Canvas.TextRect(ARect, 2, ARect.Top+2, ListBox1.Items[Index]);  //Draw Itemtext
 
end;
 
end;
</source>  
+
</syntaxhighlight>
 
{{Note|'''Parameters of ListBoxDrawItem:'''<br><br>
 
{{Note|'''Parameters of ListBoxDrawItem:'''<br><br>
'''Control:'''<br> If multiple controls (E.g. multiple ListBoxes) access this event handle, you know which threw this event. You could in our example, instead of '''<code>ListBox1.Canvas.FillRect(ARect)</code>''' also '''<code>TListBox(Control).Canvas.FillRect(ARect)</code>''' write, where you should query still possible before, whether it is a TListBox:
+
'''Control:'''<br> If multiple controls (E.g. multiple ListBoxes) access this event handle, you know which threw this event. You could in our example, instead of '''<syntaxhighlight lang=pascal>ListBox1.Canvas.FillRect(ARect)</syntaxhighlight>''' also '''<syntaxhighlight lang=pascal>TListBox(Control).Canvas.FillRect(ARect)</syntaxhighlight>''' write, where you should query still possible before, whether it is a TListBox:
<source>
+
<syntaxhighlight lang=pascal>
 
   if Control is TListBox then
 
   if Control is TListBox then
 
     TListBox(Control).Canvas.FillRect(ARect);     
 
     TListBox(Control).Canvas.FillRect(ARect);     
</source>
+
</syntaxhighlight>
 
'''Index:'''  
 
'''Index:'''  
Specifies the item location, so you have access to the string '''<code><ListBox>.Items[Index]</code>'''.<br>
+
Specifies the item location, so you have access to the string '''<syntaxhighlight lang=pascal><ListBox>.Items[Index]</syntaxhighlight>'''.<br>
 
'''ARect:'''
 
'''ARect:'''
 
Describes the rectangle, which is necessary for drawing the background.<br>
 
Describes the rectangle, which is necessary for drawing the background.<br>
Line 133: Line 126:
 
==See also==
 
==See also==
 
* [[doc:lcl/stdctrls/tlistbox.html|TListBox doc]]
 
* [[doc:lcl/stdctrls/tlistbox.html|TListBox doc]]
 +
* [[TDBListBox]]
 +
* [[ListBox with separators]]
 +
* [http://forum.codecall.net/topic/73705-the-basic-working-with-tlistbox/ tutorial about TListBox]
  
 
{{LCL Components}}
 
{{LCL Components}}

Latest revision as of 11:14, 19 July 2021

Deutsch (de) English (en) suomi (fi) français (fr) 日本語 (ja)

A TListBox tlistbox.png is a component that shows a (scrollable) list of (short) strings where user is to select one. It is available from the Standard tab of the Component Palette.

In the TListBox, the stored strings are stored in the property Items, that is of type TStrings. Thus you can assign or remove strings in the ListBox, as in a TStringList or its parent TStrings.

Here are a few examples of how to use a TListBox ListBox1 on a form Form1:

Fill ListBox

by the Object Inspector

  • Select the ListBox on your form with one click.
  • Go in the Object Inspector in the Properties tab on the property Items.
  • Click on the button with the three dots. The String Editor opens.
  • Enter your text and confirm your work with OK.

by code in button click

Add your form a TButton with the name btnFill and caption fill ListBox. In the event handler OnClick of the button, you write the following code:

procedure TForm1.btnFillClick(Sender: TObject);
begin
  ListBox1.Items.Clear;             //Delete all existing strings
  ListBox1.Items.Add('First line');
  ListBox1.Items.Add('Line with random number '+IntToStr(Random(100)));
  ListBox1.Items.Add('Third line');
  ListBox1.Items.Add('Even a random number '+IntToStr(Random(100)));
end;

Assignment of a StringList

Add your form a TButton with the name btnFill and caption fill ListBox. In the event handler OnClick of the button, you write the following code:

procedure TForm1.btnFillClick(Sender: TObject);
var
  myStringList: TStringList;
begin
  myStringList:=TStringList.Create;               //Create my StringList
  myStringList.Add('This is the first line.');   //This add a row
  myStringList.Add('This is the second first line.');
  myStringList.Add('This is the third line.');
  myStringList.Add('etc.');
  ListBox1.Items.Assign(myStringList);            //assign the ListBox1 the text content of my StringList
  myStringList.Free;                              //Free my StringList in memory 
end;

Add string

  • Extend the example Fill ListBox by code in button click to a TEdit and a TButton with the name btnAdd and caption add string. Change of Edit1 the property Text to "" - empty string.
  • In the event handler OnClick of the button, you write the following code:
procedure TForm1.btnAddClick(Sender: TObject);
begin
  ListBox1.Items.Add(Edit1.Text);
  Edit1.Text:='';
end;

Delete string

By default is set that you can select only one row in your list box. Do you want to select several of the lines in your ListBox, you would have the property MultiSelect to make True.

at ItemIndex

  • Extend the example Add string to a TButton with the name "btnDel" and caption "delete string".
  • In the event handler OnClick of the button, you write the following code:
procedure TForm1.btnDelClick(Sender: TObject);
begin
  if ListBox1.ItemIndex > -1 then    //Delete only when a string in the listbox is selected
    ListBox1.Items.Delete(ListBox1.ItemIndex);
end;

all selected strings

  • Extend the example Add string to a TButton with the name "btnDel" and caption "delete string".
  • In the event handler OnClick of the button, you write the following code:
procedure TForm1.btnDelClick(Sender: TObject);
var
  i: Integer;
begin
  if ListBox1.SelCount > 0 then                 //Delete only if at least one string in the list box is selected
    for i:=ListBox1.Items.Count - 1 downto 0 do //Iterate through all the items
      if ListBox1.Selected[i] then              //If selected...
        ListBox1.Items.Delete(i);               //...delete the item (String)
end;

Owner-drawn ListBox

In general, it is advantageous to let the ListBox follow the theme set by the user. In some cases (for example, to program a game with a colorful surface), you can deviate from this standard and draw the control according to your own choice. You can try this now:

  • You can modify the previous sample or create a new application with a TListBox ListBox1.
  • In the Object Inspector, change ListBox1 property Style to lbOwnerDrawFixed.
  • With the Object Inspector, tab events, create the event handler for the event OnDrawItem, by clicking on the button [...].
  • You add the following code to the handler:
procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer;
  ARect: TRect; State: TOwnerDrawState);
var
  aColor: TColor;                       //Background color
begin
  if (Index mod 2 = 0)                  //Index tells which item it is
    then aColor:=$FFFFFF                //every second item gets white as the background color
    else aColor:=$EEEEFF;               //every second item gets pink background color
  if odSelected in State then aColor:=$0000FF;  //If item is selected, then red as background color
  ListBox1.Canvas.Brush.Color:=aColor;  //Set background color
  ListBox1.Canvas.FillRect(ARect);      //Draw a filled rectangle

  ListBox1.Canvas.Font.Bold:=True;      //Set the font to "bold"
  ListBox1.Canvas.TextRect(ARect, 2, ARect.Top+2, ListBox1.Items[Index]);  //Draw Itemtext
end;

Light bulb  Note: Parameters of ListBoxDrawItem:

Control:
If multiple controls (E.g. multiple ListBoxes) access this event handle, you know which threw this event. You could in our example, instead of
ListBox1.Canvas.FillRect(ARect)
also
TListBox(Control).Canvas.FillRect(ARect)
write, where you should query still possible before, whether it is a TListBox:
  if Control is TListBox then
    TListBox(Control).Canvas.FillRect(ARect);

Index:

Specifies the item location, so you have access to the string
<ListBox>.Items[Index]
.

ARect: Describes the rectangle, which is necessary for drawing the background.
State: Status of the items, whether normal, focused, selected etc.

  • Your example could look like:

ListBoxBsp1.png -> ListBoxBsp2.png

See also


LCL Components
Component Tab Components
Standard TMainMenu • TPopupMenu • TButton • TLabel • TEdit • TMemo • TToggleBox • TCheckBox • TRadioButton • TListBox • TComboBox • TScrollBar • TGroupBox • TRadioGroup • TCheckGroup • TPanel • TFrame • TActionList
Additional TBitBtn • TSpeedButton • TStaticText • TImage • TShape • TBevel • TPaintBox • TNotebook • TLabeledEdit • TSplitter • TTrayIcon • TControlBar • TFlowPanel • TMaskEdit • TCheckListBox • TScrollBox • TApplicationProperties • TStringGrid • TDrawGrid • TPairSplitter • TColorBox • TColorListBox • TValueListEditor
Common Controls TTrackBar • TProgressBar • TTreeView • TListView • TStatusBar • TToolBar • TCoolBar • TUpDown • TPageControl • TTabControl • THeaderControl • TImageList • TPopupNotifier • TDateTimePicker
Dialogs TOpenDialog • TSaveDialog • TSelectDirectoryDialog • TColorDialog • TFontDialog • TFindDialog • TReplaceDialog • TTaskDialog • TOpenPictureDialog • TSavePictureDialog • TCalendarDialog • TCalculatorDialog • TPrinterSetupDialog • TPrintDialog • TPageSetupDialog
Data Controls TDBNavigator • TDBText • TDBEdit • TDBMemo • TDBImage • TDBListBox • TDBLookupListBox • TDBComboBox • TDBLookupComboBox • TDBCheckBox • TDBRadioGroup • TDBCalendar • TDBGroupBox • TDBGrid • TDBDateTimePicker
Data Access TDataSource • TCSVDataSet • TSdfDataSet • TBufDataset • TFixedFormatDataSet • TDbf • TMemDataset
System TTimer • TIdleTimer • TLazComponentQueue • THTMLHelpDatabase • THTMLBrowserHelpViewer • TAsyncProcess • TProcessUTF8 • TProcess • TSimpleIPCClient • TSimpleIPCServer • TXMLConfig • TEventLog • TServiceManager • TCHMHelpDatabase • TLHelpConnector
Misc TColorButton • TSpinEdit • TFloatSpinEdit • TArrow • TCalendar • TEditButton • TFileNameEdit • TDirectoryEdit • TDateEdit • TTimeEdit • TCalcEdit • TFileListBox • TFilterComboBox • TComboBoxEx • TCheckComboBox • TButtonPanel • TShellTreeView • TShellListView • TXMLPropStorage • TINIPropStorage • TJSONPropStorage • TIDEDialogLayoutStorage • TMRUManager • TStrHolder
LazControls TCheckBoxThemed • TDividerBevel • TExtendedNotebook • TListFilterEdit • TListViewFilterEdit • TLvlGraphControl • TShortPathEdit • TSpinEditEx • TFloatSpinEditEx • TTreeFilterEdit • TExtendedTabControl •
RTTI TTIEdit • TTIComboBox • TTIButton • TTICheckBox • TTILabel • TTIGroupBox • TTIRadioGroup • TTICheckGroup • TTICheckListBox • TTIListBox • TTIMemo • TTICalendar • TTIImage • TTIFloatSpinEdit • TTISpinEdit • TTITrackBar • TTIProgressBar • TTIMaskEdit • TTIColorButton • TMultiPropertyLink • TTIPropertyGrid • TTIGrid
SQLdb TSQLQuery • TSQLTransaction • TSQLScript • TSQLConnector • TMSSQLConnection • TSybaseConnection • TPQConnection • TPQTEventMonitor • TOracleConnection • TODBCConnection • TMySQL40Connection • TMySQL41Connection • TMySQL50Connection • TMySQL51Connection • TMySQL55Connection • TMySQL56Connection • TMySQL57Connection • TSQLite3Connection • TIBConnection • TFBAdmin • TFBEventMonitor • TSQLDBLibraryLoader
Pascal Script TPSScript • TPSScriptDebugger • TPSDllPlugin • TPSImport_Classes • TPSImport_DateUtils • TPSImport_ComObj • TPSImport_DB • TPSImport_Forms • TPSImport_Controls • TPSImport_StdCtrls • TPSCustomPlugin
SynEdit TSynEdit • TSynCompletion • TSynAutoComplete • TSynMacroRecorder • TSynExporterHTML • TSynPluginSyncroEdit • TSynPasSyn • TSynFreePascalSyn • TSynCppSyn • TSynJavaSyn • TSynPerlSyn • TSynHTMLSyn • TSynXMLSyn • TSynLFMSyn • TSynDiffSyn • TSynUNIXShellScriptSyn • TSynCssSyn • TSynPHPSyn • TSynTeXSyn • TSynSQLSyn • TSynPythonSyn • TSynVBSyn • TSynAnySyn • TSynMultiSyn • TSynBatSyn • TSynIniSyn • TSynPoSyn
Chart TChart • TListChartSource • TRandomChartSource • TUserDefinedChartSource • TCalculatedChartSource • TDbChartSource • TChartToolset • TChartAxisTransformations • TChartStyles • TChartLegendPanel • TChartNavScrollBar • TChartNavPanel • TIntervalChartSource • TDateTimeIntervalChartSource • TChartListBox • TChartExtentLink • TChartImageList
IPro TIpFileDataProvider • TIpHtmlDataProvider • TIpHttpDataProvider • TIpHtmlPanel
Virtual Controls TVirtualDrawTree • TVirtualStringTree • TVTHeaderPopupMenu