Populating a Matlab GUI Listbox from Database Valu

2019-08-12 04:25发布

问题:

I am relatively new to GUI's in Matlab, and I have created a simple GUI using GUIDE. I want to connect to a database (already defined and working!) and populate a listbox with the values from the database so the user can choose which to use (in this case they are chemical compounds). I haven't been able to find a good tutorial or clues on how to populate the listbox in this way. So far, I have:

function load_listbox(hObject,handles) 

    conn = database('antoine_db','','');
    setdbprefs('datareturnformat','structure'); %sets the db preferences to a structure
    query = 'SELECT ID,"Compound Name" FROM antoine_data ORDER BY ID';

    result = fetch(conn,query);

    %%The following creates a structure containing the names and ID's
    %%of everything in the database
    data = struct([]);
    for i=1:length(result.ID)
        data(i).id =   result.ID(i);
        data(i).name = char(result.CompoundName(i));
    end


    names = data.name;
    handles.compounds = names;
    whos;
    set(handles.listbox1,'String',handles.compounds,'Value',1);

    handles.output = hObject;

    % Update handles structure
    guidata(hObject, handles);

end

What would be the simplest way to populate a listbox from a database (or large array) like this? As of right now, the listbox is populated with only the first item in names, which is because somehow names contains only the first item. Although, if I just display 'data.name', I get the entire list of 300 items in the list!

回答1:

I got it! So, the problem was that I was converting the data.name to a character -> originally it was a cell. Thus, I added names(i) = data(i).name; in the for loop, and removed names=data.name; It is now populated with all of the names of the compound! The working function looks like this:

function load_listbox(hObject,handles) 

    conn = database('antoine_db','','');
    setdbprefs('datareturnformat','structure'); %sets the db preferences to a structure
    query = 'SELECT ID,"Compound Name" FROM antoine_data ORDER BY ID';

    result = fetch(conn,query);

    %%The following creates a structure containing the names and ID's
    %%of everything in the database
    data = struct([]);
    for i=1:length(result.ID)
        data(i).id =   result.ID(i);
        data(i).name = (result.CompoundName(i));        %this is a cell
        names(i) = data(i).name;
    end



    handles.compounds = names;
    set(handles.listbox1,'String',handles.compounds,'Value',1);

handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

end