Objective : Save the combobox selection into a list of strings and then being able to affect the combobox at the correct index from said string.
Affecting the list of strings :lstExample(i) = cmbExample.SelectionBoxItem
This gets the string value of the combobox which is meant to be stored in a database. After that, let's say the index of the combobox is set to -1.
It is now needed to take the string value from the list and put it back in the combobox.
Important facts :
CmbExample.FindString
and CmbExample.IndexOf()
do not seem to existCmbExample.SelectedItem = lstExample(i)
does not workCmbExample.FindName(lstExample(i))
is always returning 0 Are there any built in methods which allow to do such treatment ?
You can find the Index of an item in a collection with the IndexOf method:
index = cmbExample.Items.IndexOf(key)
The ComboBox does not natively contain strings: it can contain any type, including simple types like strings or complex types containing multiple properties (e.g. a Person class)
Typically you'd fill the ComboBox by data binding to a collection rather than adding items directly. This collection will usually contain a more complicated data type than a string, although bare strings can work too.
You can then find the index of a specific item by searching that collection with the IndexOf method rather than searching ComboBox.Items directly:
Assume a collection of strings:
Dim data As New ObservableCollection(Of String)
Set to our ComboBox's DataContext:
cb1.DataContext = data
<ComboBox x:Name="cb1" ItemsSource={Binding} />
Then we can find X's index by searching data:
IndexOfX= data.IndexOf(X)
More typically the ComboBox's data would be a collection in a property of a larger data object which also contains the rest of the data for the Page. That overall data object would be set as the Page's DataContext and inherited by the ComboBox.
It's not clear to me what the relation is between lstExample and cmbExample, but you can likely bind them to the same (or related data) and then bind them to each other and let Xaml's data binding system keep them in sync.
Select an item from the following ListBox and the ComboBox will follow:
<ComboBox x:Name="cmbExample" ItemsSource={Binding} SelectedIndex="{Binding ElementName=lstExample, Path=SelectedIndex}" />
<ListBox x:Name="lstExample" ItemsSource={Binding} />
The bound items don't have to display the same thing. The ObservableCollection can contain a more complex type (e.g. a Person with Name, PhoneNumber, and Address properties) and the ListBox can display the Names while the ComboBox can display the PhoneNumber and the Address.
Much of the power of Xaml and its advantage over WinForms comes from DataBinding. I strongly recommend you learn how to do so. You can start with the documentation in the Data binding (XAML) topics on MSDN.