How to Add Element/Item to Listbox in Matlab GUI (push button, listbox)

83 views (last 30 days)
Hi there, I'm trying to add new (and only new) elements to my initially empty GUI Listbox, but it just doesn't work out. Here's my code for the pushbutton callback :
function pushbutton2_Callback(hObject, eventdata, handles)
Items_2 = {};
handles = guidata(hObject);
folder = handles.folder;
pathname = folder;
Item_1 = handles.selectedItemStr; %Comes from another listbox.
guidata(hObject, handles)
while ~strcmpi(Items_2, Item_1) %When the Item_1 is allready in Items_2, the While Loop ends by itself and Items_2 stays the same.
Items_2 = [Item_1, Items_2]; % However, in the contrary, Item_1 is added to the Items_2 (cell arrays of string characters)
set(handles.listbox2,'String',Items_2); %Update the list in Listbox2.
Here's my code for the listbox 2 callback :
function listbox2_Callback(hObject, eventdata, handles)
%I don't think I need to do this, but I do it anyway.
list = get(handles,'String');
When I run my GUI, it shows no error, but the list doesn't update nor doesn't add any new item.
Thanks for the help!

Accepted Answer

Geoff Hayes
Geoff Hayes on 17 Jun 2019
Thomas - perhaps the condition
~strcmpi(Items_2, Item_1)
is never evaluating to true and so you never enter the body of the while loop. Part of the problem may be because Items_2 is always initialized to an empty cell array (is this intentional?) and is never set to what is currently in your list. Note that if I try the above, with
g = {};
strcmpi(g, 'hello')
then an empty array is I suspect that is the real problem. The condition is never satisfied. Try doing something like the following instead
function pushbutton2_Callback(hObject, eventdata, handles)
selectedString = handles.selectedItemStr; % assumed to be a string
listBox2Data = get(handles.listbox2,'String');
if isempty(listBox2Data) || ~any(strcmpi(listBox2Data, selectedString))
listBox2Data = [selectedString, listBox2Data];
No need for a while loop in this case. Note that we use the call to any since the strcmpi may return an array of 0 or 1s for each element in the list box. any will return true if at least one of these elements is a one (indicating that the selected string is already in the list). If the call returns 0 (i.e. no element in list matches the selected string) then we add the item to the list.

More Answers (0)


Find more on Interactive Control and Callbacks 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!