Reputation: 141
I want to populate a listbox with a list of servers in a flat file based on the selection made from a combobox dropdown. This is what i have but its not populating the listbox.. thanks!
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ComboBox.SelectedItem.ToString() == "Choice1")
{
Listbox1.ItemsSource = null;
Listbox1.Items.Clear();
Listbox1.ItemsSource = File.ReadAllLines(@"C:\temp\serverlist1.txt");
}
return;
}
Here's the XAML,
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ComboBox x:Name="ComboBox" Grid.Column="0" SelectionChanged="ComboBox_SelectionChanged">
<ComboBoxItem Content="Choice1"/>
<ComboBoxItem Content="Choice2"/>
</ComboBox>
<ListBox x:Name="Listbox1" Grid.Column="1" />
</Grid>
Upvotes: 0
Views: 97
Reputation: 487
The only mistake in your code is that you are comparing ComboBox SelectedItem string with "Choice", which won't be equal ever. You need to parse SelectedItem to ComboBoxItem first and then compare Content of the ComboBoxItem to the expected string. Following is the demonstration,
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (((ComboBoxItem)comboBox1.SelectedItem).Content.Equals("Choice1"))
{
listBox1.ItemsSource = null;
listBox1.Items.Clear();
listBox1.ItemsSource = File.ReadAllLines(@"C:\application1\serverlist1.txt");
}
return;
}
Upvotes: 2