MATLAB: List box dissapearing when removing items from it.

listboxvalue

[EDIT: 20110616 14:29 CDT – reformat – WDR]
I am using this bit of code to remove items from a listbox. however if i remove all of the items and then try and add another the list box itself dissapears.s I get this warning:
Warning: multi-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.
The code is as follows. I think I it not allowing indices to be zero. but I don't know what to put in the code to prevent the dissapearing of the listbox.
Here is the code:
____________________________________________________________
% --- Executes on button press in remove_button.
function remove_button_Callback(hObject, eventdata, handles)
% hObject handle to remove_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%selected item reorganizes the listbox index
selected = get(handles.listbox2,'Value');
prev_str = get(handles.listbox2, 'String');
len = length(prev_str);
if len > 0
if selected(1) == 1
indices = [(selected(end)+1):length(prev_str)];
else
indices = [1:(selected(1)-1) (selected(end)+1):length(prev_str)];
end
% elseif len == 0
% set(handles.listbox2, 'Value',1);
prev_str = prev_str(indices);
set(handles.listbox2, 'String', prev_str, 'Value', min(selected, length(prev_str)));
end
__________________________________________________________
How do I go about keeping the list box in the GUI when nothing is in it?
Thanks
Bill

Best Answer

I've done similar things, having a "Remove" button, if clicked, it removes the highlighted item in the list box. Here is my code for your reference. I remember that I have to take care of the synchronization of the 'string' and 'value' property of the list box. Also, you need to take care when the list box is empty.
contents = get(handles.lbDataItemSelected,'String');
if length(contents)<1; return; end; %if already empty, do nothing
Index=get(handles.lbDataItemSelected,'Value');
contents(Index)=[]; %remove the item
Value=Index-1;
if Value<1; Value=1;end %take care of exception
set(handles.lbDataItemSelected,'String',contents,'Value',Value);