Drop down in uitable to work like excel
4 views (last 30 days)
Show older comments
I have an uitable and I want to have certain cells with a drop down. I know that this is done by using the functions categorical and table. The problem is that I need the table to accept empty values and show the empty values as a blank cell with the drop down functionality. If I add the empty option to a categorical this will show as <undefined>
Data = cell(21,2);
for i = 1:length(Data)
for j = 1:length(Data)
Data{i,j} = "";
end
end
fig = uifigure;
tab = uitable(fig);
opts = categorical({'1','2',''});
Data{2,1} = opts(3);
Column1 = Data(:,1);
Column2 = Data(:,2);
tab.Data = table(Column1,Column2);
By making the Columns editable and changing the <undefined> value it will show always one of the non-empty options entered in the categorical function and not allowing the cell to be empty (or <undefined>) anymore:
Is there a way to allow this types of cells to work like the drop downs works in Excel?
Thank you beforehand.
0 Comments
Answers (1)
Saurav
on 3 Oct 2024
It seems there is a need to create dropdown cells in a “uitable” that can also accept empty values. However, there are some categorical limitations like that the categorical function does not support empty strings (" "), empty character vectors (''), or missing strings (<missing>) as category names. These are automatically converted to undefined categorical values unless explicitly categorized.
For further details, please refer to the documentation:
The following code provides a workaround:
% Create a cell array to hold data
Data = cell(21,2);
% Initialize all cells with a placeholder string
for i = 1:length(Data)
for j = 1:size(Data, 2)
Data{i,j} = "Select";
end
end
% Create a figure and a uitable
fig = uifigure;
tab = uitable(fig);
% Define the options for the drop-down including a placeholder for empty
opts = {'Select', '1', '2'};
% Convert the cell array to a string array
strData = string(Data);
% Convert columns to categorical arrays
Column1 = categorical(strData(:,1), opts, 'Ordinal', true);
Column2 = categorical(strData(:,2), opts, 'Ordinal', true);
% Assign the data to the uitable
tab.Data = table(Column1, Column2);
% Set the columns to be editable
tab.ColumnEditable = true;
% Function to update display data
function updateDisplayData(src)
data = src.Data;
for i = 1:height(data)
for j = 1:width(data)
if data{i, j} == categorical("Select")
data{i, j} = categorical("");
end
end
end
src.Data = data;
end
The code can be adjusted based on specific requirements regarding which cell values need dropdown functionality.
Hope that it helps.
See Also
Categories
Find more on Develop uifigure-Based Apps 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!