Reputation: 139
What I wanted to do is make a particular string in a combobox the selectedindex. The contents of the combobox are filenames of files ina directory. This is an editable combobox. So I did
private void InitComboBoxProfiles()
{
string appDataPath1 = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string configPath1 = appDataPath1 + "/LWRF/ReaderProfiles";
string[] files = Directory.GetFiles(configPath1);
foreach( string fn in files)
{
ComboBoxProfiles.Items.Add(fn);
}
int index = -1;
foreach (ComboBoxItem cmbItem in ComboBoxProfiles.Items) //exception thrown at this line
{
index++;
if (cmbItem.Content.ToString() == "Default.xml")
{
ComboBoxProfiles.SelectedIndex = index;
break;
}
}
}
Exception:
Unable to cast object of type System.String to System.Windows.Controls.ComboBoxItem
How do I achieve my goal? thanks, saroj
Upvotes: 0
Views: 208
Reputation: 128060
As the ComboBox items are strings, you could simply set the SelectedItem property to the desired string:
ComboBoxProfiles.SelectedItem = "Default.xml";
Note that this will automatically set the SelectedIndex
property to the proper value, as SelectedItem
and SelectedIndex
will always be kept in sync.
Upvotes: 1
Reputation: 5423
The ComboBox
Items are of type string
. Change your code to this :
foreach (string cmbItem in ComboBoxProfiles.Items)
{
index++;
if (cmbItem == "Default.xml")
{
ComboBoxProfiles.SelectedIndex = index;
break;
}
}
and better than looping :
ComboBoxProfiles.SelectedIndex = ComboBoxProfiles.Items.IndexOf("Default.xml");
Upvotes: 0