How to automatically generate rows in uitable from edit box?

6 views (last 30 days)
Hi, hope this community can help me to solve this problem. I've created an UI with one edit box and a table ( rows by 3). Whenever i insert a value into the edit box , i want the row of the table is equal to the number I've inserted.
  • Let say i put 5 in the edit box
  • The table will automatically generate 5 rows
  • Column 1 of the table will automatically fill with 1:5
Hope you guys can help me to figure how to make it.

Answers (1)

Geoff Hayes
Geoff Hayes on 30 Nov 2014
Edited: Geoff Hayes on 2 Dec 2014
Nik - if we assume that your edit box is named edit1 and your table is named uitable1, then in your edit box callback, you could do something like
function edit1_Callback(hObject, eventdata, handles)
numRows = str2num(char(get(hObject,'String')));
if ~isempty(numRows) && numRows>0
numRows = ceil(numRows);
data = zeros(5,3);
data(:,1) = (1:5)';
% convert the values matrix to a cell array
valuesAsCell = mat2cell(data);
% update the table
set(handles.uitable1,'Data',valuesAsCell{:});
end
In the above, we get the string input from the edit box and convert it to a number. If it is numeric (non-empty) and positive, we create the data matrix and populate the first column with the numbers from 1 to 5 with the remaining entries set to zero. We then convert it to a cell matrix and set the table.
EDIT
Wrapped the get(hObject,'String') in char to convert the return type from the get from a cell array to a char/string array.
  3 Comments
Geoff Hayes
Geoff Hayes on 2 Dec 2014
I made a slight change to the above code which was causing a Requires string or character array input error because the get(hObject,'String') was returning a cell array. So the first line is now
numRows = str2num(char(get(hObject,'String')));
As for your error, without seeing your code, I don't know why there would be a problem unless you have forgotten to add an end statement to some code of the function that precedes your input1_CreateFcn.
No code is required for the input_CreateFcn so you can leave it as blank.
Diogo Queirós
Diogo Queirós on 23 Jan 2015
Edited: Diogo Queirós on 23 Jan 2015
I'm having a problem that i can't solve. I want to insert text in the first collumn, but as soon as i insert any caracter that is not a number, the cell automatically goes to NaN. Can you help me?
edit1 = str2num(char(get(hObject,'String')));
if ~isempty(edit1) && edit1>0
edit1 = ceil(edit1);
data = cell(edit1,4);
% convert the values matrix to a cell array
valuesAsCell = mat2cell(data);
% update the table
set(handles.uitable,'Data',valuesAsCell{:});
end

Sign in to comment.

Categories

Find more on Migrate GUIDE 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!