Populating a Matlab GUI Listbox from Database Values

与世无争的帅哥 提交于 2019-12-11 04:55:12

问题


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


来源:https://stackoverflow.com/questions/11493798/populating-a-matlab-gui-listbox-from-database-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!