how to get index of selected item in listbox of appdesginer

173 ビュー (過去 30 日間)
Yu Li
Yu Li 2019 年 8 月 30 日
コメント済み: Adam Danz 2019 年 11 月 19 日
I want to get the index of selected item in listbox of appdesigner.
The weakness of the solution provided here using 'ismember' function is that, if I have two items that are totally the same, the returned index is not unique. so, is there any other solutions?
  3 件のコメント
Adam Danz
Adam Danz 2019 年 8 月 31 日
The problem isn't that duplicate values are unnecessary. The problem is that there should be no difference between "apples" and "apples" so selecting either of them should result in the same outputs. Otherwise, how would the user know which "apples" to select?
In any case, I added an answer that suggests a workaround.



Adam Danz
Adam Danz 2019 年 8 月 31 日
編集済み: Adam Danz 2019 年 8 月 31 日
Continuing from comments under the question.
There is unfortunately no property of a listbox that returns the index of the selected item. The only way to get the index is by finding the selection within a list of options by using strcmp() or ismember() etc. If your list of options has duplicates and one of the duplicates was selected, there is no way to match which of the duplicates was selected.
One potential workaround in app designer is to assign unique values to the ItemsData property. When the ItemsData property is set, the Value property of a listbox returns the ItemsData selection rather than the Items selection.
fig = uifigure();
lbx = uilistbox(fig,'Items',{'Apples','Apples','Pears','Bananas'}, ...
Now when the 2nd "Apples" is selected,
ans =
  2 件のコメント
Adam Danz
Adam Danz 2019 年 8 月 31 日
Glad I could help!


その他の回答 (1 件)

Marvin Seifert
Marvin Seifert 2019 年 11 月 19 日
You cant get the index directly from the listbox class but you can get the index from the mousclick event. In the callback function for the listbox you can do
indices = event.Value;
This works for multiple selections as well.
  3 件のコメント
Adam Danz
Adam Danz 2019 年 11 月 19 日
Yes, with the ItemsData you can output the pre-established index. But if there is an error in the numbering of the the ItemsData, the true index will not be returned. But your method of indexing the number of list items is a good approach.



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!

Translated by