correctly erasing items from a listbox

I am trying to erase some listings from a listBox. however, when I push the appropriate button I receive the following warning:
Warning: multi-selection listbox control requires that Value be an integer within String range
and the listBox control doesn't get rendered. Any ideas for a fix? here is the code of the button's callback :
function btnRemovePNU_FromUse_Callback(hObject, eventdata, handles)
% hObject handle to btnRemovePNU_FromUse (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
PNUList = handles.liPNU_toUse;
indexedPNU = get(PNUList,'value');
PNUnames = get(PNUList,'String');
PNUnames(indexedPNU) = [];
set(PNUList,'String',PNUnames);

 Accepted Answer

After you delete the items from the 'String' property, you need to update the 'Value' property as well.
For example, if you initially had 3 items, and you selected the 3rd one, then 'value' is 3. Then you delete it, and now you have two items left, but the value is still = 3. This is the problem.
Update the 'value' and you'll be fine:
set(PNUList,'String',PNUnames, 'Value', 1);

3 Comments

This is ok too (if you are allowing multiple or empty selections)
set(PNUList,'String',PNUnames, 'Value', []);
Thanks Teja!
I took your answer and updated the value to be at one place before the erased text:
function btnRemovePNU_FromUse_Callback(hObject, eventdata, handles)
% hObject handle to btnRemovePNU_FromUse (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
PNUList = handles.liPNU_toUse;
indexedPNU = get(PNUList,'value');
newPlace = indexedPNU(1)-1;
if (newPlace <=0) newPlace = 1; end
PNUnames = get(PNUList,'String');
if ~isempty(PNUnames)
PNUnames(indexedPNU) = [];
set(PNUList,'String',PNUnames,'value', newPlace);
end
Thomas Côté
Thomas Côté on 17 Jun 2019
Edited: Thomas Côté on 17 Jun 2019
10000 years later, thank you.
It was helpful for my own code.

Sign in to comment.

More Answers (0)

Categories

Find more on Interactive Control and Callbacks in Help Center and File Exchange

Tags

Asked:

roi
on 21 May 2011

Edited:

on 17 Jun 2019

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!