ValueIndex of ListBox can not be set to 1
6 views (last 30 days)
Show older comments
I created a 'Listbox' in AppDesigner
I can preset the selected items in the listbox by setting the value indices, for example
- app.ListBox.ValueIndex = [2 3]
- app.ListBox.ValueIndex = [3 2]
correctly preselects items with indices 2 and 3.
In addition, I can also select no item with
- app.ListBox.ValueIndex = []
The code works for all index value combinations, as long as I do not include index value equal to 1.
In other words, I can not set index value equal to 1, i.e.
- app.ListBox.ValueIndex = [1]
- app.ListBox.ValueIndex = [1 2]
- app.ListBox.ValueIndex = [1 2 3]
All give the error 'ValueIndex' must be [] or a 1-D vector of positive integers each representing an index in 'Items'.
Any idea what can be wrong here?
5 Comments
dpb
on 5 Mar 2025
That is the behavior as described by @Cris LaPierre in her answer. What I didn't recognize from the description is that any occurrence of "1" in the list errors; not just if only "1" is provided.
Owing to this, my suggested workaround doesn't work if the idea is to pick item 1 along with some others.
However, it's still pretty trivial to code; just use indirect addressing...
function startupFcn(app)
iwant=[1 3]; % the list of wanted pre-selected items
app.ListBox.Value=app.ListBox.Items(iwant); % set the Value list by lookup into Items
end
Answers (1)
Cris LaPierre
on 4 Mar 2025
This appears to be a bug with ListBox in R2023b. When 'multiselect' is enabled, it throws the exception if the index is <=1 instead of <1.
This has been fixed in newer versions of MATLAB, but apparently the fix never made it back to R2023b.
The recommended workaround for now is to reference items by name instead of index. So assuming this is the listbox,

the corresponding code would be
app.ListBox.Value = {'Item 1'}
app.ListBox.Value = {'Item 1' 'Item 2'}
app.ListBox.Value = {'Item 1' 'Item 2' 'Item 3'}
I've shared a sample app.
4 Comments
dpb
on 4 Mar 2025
@Thanks, Cris...I'm holding @ R2021b at present to continue to support an app on a system controlled by an IT group so couldn't check it out.
See Also
Categories
Find more on Develop uifigure-Based Apps in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!