C# change the selected index of a ComboBox item using LINQ - c#

Im not sure if the title represent the problem I have. The explanation here below should be clearer.
I cannot get my code to select the correct value in the ComboBox with the data from my List. I checked for similar problems here in SO but after reading several I cannot find one that matches my problem.
I fill the list with the follwing code:
if (roleComboBox.SelectionBoxItem.Equals("Player"))
{
memberID++;
Player player = new Player(memberID, team, firstName, lastName, age, salary, yearsActive, position, minutesPerGame);
players.Add(player);
PrintList();
}
Now I want to retrieve the data from the List and put it back into the TextBox/ComboBox it came from so I can change the data and put it back into the List (kinda a modify option). I have a different ComboBox with where I select an ID which matches a memberID which in its turn retrieves the data from the List. I use the following code for that:
private void ModifyComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int modifyID = int.Parse(modifyComboBox.SelectedItem.ToString());
var player = players.Where(p => p.memberID == modifyID);
teamComboBox.SelectedValue = player.Select(p => p.team).FirstOrDefault(); // this isnt working as intended
firstNameTextBox.Text = player.Select(p => p.firstName).FirstOrDefault();
lastNameTextBox.Text = player.Select(p => p.lastName).FirstOrDefault();
ageTextBox.Text = player.Select(p => p.age.ToString()).FirstOrDefault();
salaryTextBox.Text = player.Select(p => p.salary.ToString()).FirstOrDefault();
yearsActiveTextBox.Text = player.Select(p => p.yearsActive.ToString()).FirstOrDefault();
minutesPerGameTextBox.Text = player.Select(p => p.minutesPerGame.ToString()).FirstOrDefault();
}
While the TextBoxes get filled with the correct data the ComboBox just gets blank.
This is de XAML code for the ComboBox if needed:
<ComboBox x:Name="teamComboBox" HorizontalAlignment="Left" Margin="200,38,0,0" VerticalAlignment="Top" Width="220">
<ComboBoxItem IsSelected="True">-Choose a team-</ComboBoxItem>
<ComboBoxItem>Minnesota Timberwolves</ComboBoxItem>
<ComboBoxItem>Charlotte Hornets</ComboBoxItem>
<ComboBoxItem>LA Lakers</ComboBoxItem>
</ComboBox>

In this case, the type of SelectedValue needs is ComboBoxItem instead of the string type you passed. If you want to set the SelectedValue programmatically, you can set the SelectedValuePath of teamComboBox as "Content" first, it means to set/get the Content of the ComboBoxItem(ie the string you set for the ComboBoxItem). Then you can set your p.team to SelectedValue. For example:
.xaml:
<ComboBox x:Name="teamComboBox" HorizontalAlignment="Left" SelectedValuePath="Content" Margin="200,38,0,0" VerticalAlignment="Top" Width="220">
<ComboBoxItem IsSelected="True">-Choose a team-</ComboBoxItem>
<ComboBoxItem>Minnesota Timberwolves</ComboBoxItem>
<ComboBoxItem>Charlotte Hornets</ComboBoxItem>
<ComboBoxItem>LA Lakers</ComboBoxItem>
</ComboBox>

Related

Set combobox Item in code Behind UWP

I have seen how to select the item from the index by code behind, but how can i select it from code behind knowing the string of the item?
combobox code xaml:
<ComboBox x:Name="ComboBoxOne" VerticalAlignment="Center" HorizontalAlignment="Center" Height="40" Width="200">
<ComboBoxItem Content="blue"/>
<ComboBoxItem Content="red"/>
<ComboBoxItem Content="green"/>
</ComboBox>
combobox code behind:
ComboBoxOne.SelectedIndex = 1;
But how to select the item knowing for example green? Is possible?
I tried with ComboBoxOne.PlaceholderText
ComboBoxOne.PlaceholderText="green"
But then I can not use the selecteditem.
Thanks in advance!
First you need to get the Items of the ComboBox as a List to find the Index of the item that you want to select by string. Since this will be a List<String> you can do something like below.
List<String> lstItems = ComboBoxOne.Items
.Cast<ComboBoxItem>()
.Select(item => item.Content.ToString())
.ToList();
and then you can get the index using Linq and assign it to Selected Index. Like below.
ComboBoxOne.SelectedIndex = lstItems.FindIndex(a => a.Equals("green"));
Good Luck.

C# - Filtering an ObservableCollection via subfield

I have the following code:
SubjectsToChooseFrom = new ObservableCollection<SubjectDTO>(_model.Subjects);
SubjectsToChooseFrom = SubjectsToChooseFrom.Where(x => x.Id == (int)CurrentProgId);
SubjectsToChooseFrom is bound to a ComboBox. After this, only one element gets shown in the box instead of a list. Why is this, and how can I make sure all the values where x.Id == (int)CurrentProgId stay in SubjectsToChooseFrom?
UPDATE
XAML and code as requested:
<ComboBox Text="Choose program" Margin="5" Grid.Row="1" Grid.Column="1" ItemsSource="{Binding SubjectsToChooseFrom}"
SelectedValue="{Binding CurrentSubjectId, Mode=TwoWay}"
SelectedValuePath="Id"
DisplayMemberPath="SubjectName">
</ComboBox>
Declaration:
private IEnumerable<SubjectDTO> _subjectsToChooseFrom;
public IEnumerable<SubjectDTO> SubjectsToChooseFrom
{
get
{
return _subjectsToChooseFrom;
}
set
{
_subjectsToChooseFrom = value;
OnPropertyChanged();
}
}
Where returns an IQueryable. You need to use ToList() or ToArray() etc. to materialize the results of this query.
If you're using MVVM, much better is to expose both your collections as public properties and raise PropertyChanged whenever these collections change for any reason. You can then bind your ComboBoxes to these properties and they'll automatically get updated.
I ended up doing this by hand:
await _model.LoadAsync();
SubjectsToChooseFrom = new ObservableCollection<SubjectDTO>(_model.Subjects);
ObservableCollection<SubjectDTO> temp = new ObservableCollection<SubjectDTO>();
foreach (var subject in SubjectsToChooseFrom) {
if(subject.ProgId == CurrentProgId)
{
temp.Add(subject);
}
}
SubjectsToChooseFrom = temp;

Passing a value from a combobox, populated from an ObservableCollection into another method UWP

I have a combobox in my main page.xmal, it is populated from an ObservableCollection and displays a list of Country Names. What I want to happen is, When the user selects the name of the country, I want to pass a code which is assoicated with each country. The Name and the Code are both stored in the ObservableCollection.
I presume I can set a property in the combobox which allow me too, set the selected item equal to the country code. Any help would be great.
<StackPanel Margin="10,100,0,0" Orientation="Vertical" >
<ComboBox Name="countryCombo"
PlaceholderText="Select Country"
ItemsSource="{x:Bind ReadInFile.CountryCodes, Mode=OneWay}"
SelectedIndex="{x:Bind ReadInFile.SelectedIndex}"
DisplayMemberPath="Name"
SelectedValuePath="Code"
MinWidth="250" Margin="5" Opacity="0.65">
</ComboBox>
<TextBox Name="CityTextBox" PlaceholderText="Enter City"/>
</StackPanel>
private async void WeatherCityButton_Click(object sender, RoutedEventArgs e)
{
var city = CityTextBox.Text.ToString();
var country = countryCombo.SelectedValuePath.ToString();
RootObject myCityWeather = await WeatherFacade.GetWeatherCity(country, city);
WeatherResultCityText.Text = myCityWeather.current_observation.display_location.city + " _ " + myCityWeather.current_observation.temp_c.ToString() + "-" + myCityWeather.current_observation.wind_kph;
}
You've already got it set up how you want it - SelectedValuePath does precisely what you describe. Once that's set, accessing the ComboBox's SelectedValue property will provide the code for the selected item.
You need only to change this line:
var country = countryCombo.SelectedValuePath.ToString();
To:
var country = countryCombo.SelectedValue.ToString();
The way you had it simply will return "Code", if I'm not mistaken, as you're retrieving the same value you put in.

Gets value from combobox in wpf binding by entity framework

I bind my combobox from entityframework and when I try to get value from my combobox by selecting value it gives back text like this {NameOfCompany = Name } How can i get only the value Name?
Thats the code in xaml
<ComboBox SelectionChanged="ComboFirma_SelectionChanged" Name="ComboFirma" Margin="109,10,10,0" Height="28" VerticalAlignment="Top">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Name="txbCombo" Text="{Binding NameOfCompany}"></TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
And I bind it like this.
var query2 = from f in model.Firmas
select new
{
f.NameOfCompany
};
ComboFirma.ItemsSource = query2.ToList();
I tried something like this to gets the selected value but always i get an exception.
var str = (TextBox)ComboFirma.Template.FindName("txbCombo", ComboFirma);
lblCompanyNameShow.Content = str.SelectedText;
ComboBox.SelectedItem will be of a item type. So normally you would need to cast SelectedItem to type of item in your collection. Now, because, in your case it's anonymous type, it's more difficult I think easiest way to get NameOfCompany is to use dynamic
dynamic selectedItem = ComboFirma.SelectedItem;
var name = selectedItem.NameOfCompany;
or you can use SelectedValue/SelectedValuePath
<ComboBox Name="ComboFirma" ... SelectedValuePath="NameOfCompany">
and in code
var name = (string)ComboFirma.SelectedValue;
Try like this
TextBlock tb1 = (TextBlock)ComboFirma.SelectedItem;
lblCompanyNameShow.Content = str.SelectedText;

WPF Unable to set Selected Item of a Combo box

I have a non-bound Combobox and I want to set its value at run time. I tried a lot but cannot achieve it. Here's the code :
<ComboBox Background="#FFB7B39D" Grid.Row="1" Height="23"
HorizontalAlignment="Right" Margin="0,26,136,0"
Name="cboWellDiameter" VerticalAlignment="Top" Width="120">
<ComboBoxItem Content="meter" IsSelected="True" />
<ComboBoxItem Content="centimeter" />
</ComboBox>
In code, I am trying with :
//VALUE of sp.wellborediameterField_unit is centimeter
// Gives -1
int index = cboWellDiameter.Items.IndexOf(sp.wellborediameterField_unit);
Console.WriteLine("Index of well bore dia unit = " + index.ToString());
cboWellDiameter.SelectedIndex = index;
// cboWellDiameter.SelectedItem = sp.wellborediameterField_unit;
// cboWellDiameter.SelectedValue = sp.wellborediameterField_unit;
SelectedItem & selectedValue has no impact. Why its not even able to find in Items ? How do I set it ?
Please help me, have several such non-bound and binded combos to set programmatically.
The issue is that your items are ComboBoxItems, not strings. So you have two options: one, use strings as the combo-box items (this allows you to set SelectedItem / SelectedValue = "meter" or "centimeter"):
<ComboBox xmlns:clr="clr-namespace:System;assembly=mscorlib">
<clr:String>meter</clr:String>
<clr:String>centimeter</clr:String>
</ComboBox>
or two, set the SelectedItem by searching for the appropriate ComboBoxItem:
cboWellDiameter.SelectedItem = cboWellDiameter.Items.OfType<ComboBoxItem>()
.FirstOrDefault(item => item.Content as string == cosp.wellborediameterField_unit);

Categories

Resources