MATLAB: Do I receive a warning when I repopulate the “listbox” uicontrol in MATLAB

deleteguiintegerlistboxMATLABrangerepopulateresetsingle-selectionstringvalue

I create a "listbox" uicontrol which contains two items:
hListBox = uicontrol('Style','listbox','String',{'item 1' 'item 2'},'Position',[20 20 100 200]);
I select the listbox item 2, and then I repopulate the listbox with a single entry:
set(hListBox,'String',{'new item'});
When I repopulate my listbox, I receive a warning:
Warning: single-selection listbox control requires that Value be an integer within String range
Control will not be rendered until all of its parameter values are valid.

Best Answer

The ability to automatically reset the "Value" property to "1" when repopulating a listbox is not available in MATLAB.
To work around this issue, set the active item in the list box to the first item before repopulating the listbox:
set(hListBox,'Value',1);
The following code provides an example where this workaround is used:
function [] = ChangeList()
% Example to demonstrate changing the items in a list
% Create two different lenght lists
list1 = {'Option 1', 'Option 2'};
list2 = {'Only Option'};
% Create a list box with the first list, set to second time.
hListBox = uicontrol('Style','listbox',...
'String',list1,...
'Position',[20 20 100 200],...
'Value',2);
% Create a button to set to list 1
hList1Button = uicontrol('Style','pushbutton',...
'String','List 1',...
'Position',[130,100,100,30],...
'Callback',@(eventObject,eventData)ChangeList(eventObject,eventData,hListBox,list1),...
'Tag','btn1');
% Create a button to set to list 2
hList2Button = uicontrol('Style','pushbutton',...
'String','List 2',...
'Position',[130,30,100,30],...
'Callback',@(eventObject,eventData)ChangeList(eventObject,eventData,hListBox,list2),...
'Tag','btn1');
end
% Create the callback
function [] = ChangeList(hObject,eventData,hListBox,list)
set(hListBox,'Value',1); % Add this line so that the list can be changed
set(hListBox,'String',list);
end