Search code examples
matlabmatlab-figurematlab-guidematlab-uitable

How to delete selected rows in uitable?


I'd like to delete selected rows of an uitable. I thought about using a checkbox for every row to select which one I want to delete.

But I can not add a column to a table with checkbox Set to false.

I get this follow error

??? Conversion to cell from logical is not possible.

Error in ==> loadTable at 7
    data(:,5) = true;

I tried with this:

 function loadTable(hTable, arrayHeaderAndData, columnFormatAtt)

        header = arrayHeaderAndData{1};
        % Add column delete
        header = [header 'Del'];
        data = arrayHeaderAndData{2};
        data(:,5) = true;
        columnFormatCases = [columnFormatCases 'logical'];

        set(hTable, 'Data',data,...
            'visible','on',...
            'ColumnWidth','auto',...
            'ColumnName',header,...
            'ColumnEditable', [false false false false],...
            'ColumnFormat', columnFormatAtt
    );


    end

Then I need to delete all rows with selected checkboxes from table. How can I do that?


Solution

  • There is no need for another column with checkbox, just to indicate which row you want to delete. I would rather use the uipushtool to add a delete button, which deletes all rows previously selected.

    function myTable 
    
    h = figure('Position',[600 400 402 100],'numbertitle','off','MenuBar','none');
    
    defaultData = rand(5,2);
    uitable(h,'Units','normalized','Position',[0 0 1 1],...
                  'Data', defaultData,... 
                  'Tag','myTable',...    
                  'ColumnName', [],'RowName',[],...
                  'CellSelectionCallback',@cellSelect);
    
    % create pushbutton to delete selected rows
    tb = uitoolbar(h);
    uipushtool(tb,'ClickedCallback',@deleteRow);
    end
    
    function cellSelect(src,evt)
    % get indices of selected rows and make them available for other callbacks
    index = evt.Indices;
    if any(index)             %loop necessary to surpress unimportant errors.
        rows = index(:,1);
        set(src,'UserData',rows);
    end
    end
    
    function deleteRow(~,~)
    th = findobj('Tag','myTable');
    % get current data
    data = get(th,'Data');
    % get indices of selected rows
    rows = get(th,'UserData');
    % create mask containing rows to keep
    mask = (1:size(data,1))';
    mask(rows) = [];
    % delete selected rows and re-write data
    data = data(mask,:);
    set(th,'Data',data);
    end