WPF Unable to set Selected Item of a Combo box - c#

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);

Related

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

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>

C# ComboBox items from an array

I've searched for answers to this for a while, but none seem to match my problem exactly.
I have a window in which I've created a ComboBox. Then in my code, I've created an array:
public string[] myList = new[] { "Item 1", "Item 2" };
Now I want to make those items the options in the ComboBox dropdown. Most of what I found suggests using DataSource and DataBind, but only DataContext is actually available.
I'm sure there's some previous step I'm missing, but I'm still pretty new to this so I'm not sure what it is.
Those answers that you found are for Winforms and you seem to be using WPF. They both have a ComboBox control, but they are actually a completely different controls with different properties. Try this (let's say you call it ComboBox1):
ComboBox1.ItemsSource = myList;
However, you usually need IDs for your items so you can use them when the user selects an item. To do that, you need to bind the ComboBox to a Dictionary instead of a List, like this:
var data = new Dictionary<int, string>{
{100, "Eggplant"},
{102, "Onion"},
{300, "Potato"},
{105, "Tomato"},
{200, "Zuccini"}
};
ComboBox1.ItemsSource = data;
ComboBox1.DisplayMemberPath = "Value";
ComboBox1.SelectedValuePath = "Key";
Now when a user selects "Onion" for example, you will get 102 by using:
int selected = (int)ComboBox1.SelectedValue;
Note: Your ComboBox1 in XAML must have no items, otherwise you will get an error.
If you prefer to keep the items in XAML instead of code-behind, there is no equivalent to the SelectedValuePath property, but you can simulate it using the Tag property like this:
<ComboBox x:Name="ComboBox1" SelectedValuePath="Tag">
<ComboBoxItem Content="Eggplant" Tag="100" />
<ComboBoxItem Content="Onion" Tag="102" />
<ComboBoxItem Content="Potato" Tag="300" />
<ComboBoxItem Content="Tomato" Tag="105" />
<ComboBoxItem Content="Zuccini" Tag="200" />
</ComboBox>
try putting ID's with mapped to each member of the string list. It will work.

WPF binding 2 properties from 1 List

So what i am trying to accomplish is that i am trying to bind 2 properties from 1 list to 2 different ComboBoxes.
code:
combobox1.DataContext = class.repository;
combobox2.DataContext = class.repository;
and in xaml
<ComboBox x:Name="combobox1" ItemsSource="{Binding Name}"/>
<ComboBox x:Name="combobox2" ItemsSource="{Binding Password}"/>
example - repository[0] = "NAME1"
The result i get is when i open ComboBox looks like:
1 item - N
2 item - A
3 item - M
and so on..
and result i want is
1 item = NAME1
2 item = NAME2
...
Thanks for replies.
If repository is a string[], you should bind the ItemsSource to the DataContext itself:
<ComboBox x:Name="combobox1" ItemsSource="{Binding}"/>
If repository is an IEnumerable<YourClass> where YourClass is a type with a Name and a Password property, you should also set the DisplayMemberPath property:
<ComboBox x:Name="combobox1" ItemsSource="{Binding}" DisplayMemberPath="Name" />
<ComboBox x:Name="combobox2" ItemsSource="{Binding}" DisplayMemberPath="Password"/>
You should use DisplayMemberPath property of the ComboBox to specify you want to see the value of propery "Name".

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.

Set an item on a WPF Combobox when ItemSource is binded to an Enum

I am having trouble assigning the a combobox item by using an enum value that the combobox source is assigned to.
The XAML
<ComboBox HorizontalAlignment="Left"
x:Name="cmbName"
VerticalAlignment="Top"
Width="120" Margin="79,48,0,0">
<ComboBox.ItemsSource>
<CompositeCollection>
<ListBoxItem Content="Please Select"/>
<CollectionContainer Collection="{Binding Source={StaticResource Enum}}" />
</CompositeCollection>
</ComboBox.ItemsSource>
</ComboBox>
The C# that is trying to set the combobox to an item in the enum
// The problem, the assignment doesn't work.
cmbName.SelectedItem = Enum.value;
I can only set a item by using the combobox SelectedIndex
cmbName.SelectedIndex = 2;
But this is hardcoding the index so if the enum changes, so will the value.
So how can I set the combobox by the enum value?
Thanks
It's very hard to tell what your problem is because you haven't fully documented your scenario. As such, all that I can do is to show you how to do what you want. As I prefer to work with properties, I won't be using any Resources for this example, but I'm sure that you'll still be able to relate this solution to your problem.
So, first we have a test enum and some properties and some initialisation:
public enum TestEnum
{
None, One, Two, Three
}
private TestEnum enumInstance = TestEnum.None;
public TestEnum EnumInstance
{
get { return enumInstance; }
set { enumInstance = value; NotifyPropertyChanged("EnumInstance"); }
}
private ObservableCollection<TestEnum> enumCollection = new ObservableCollection<TestEnum>() { TestEnum.None, TestEnum.One, TestEnum.Two, TestEnum.Three };
public ObservableCollection<TestEnum> EnumCollection
{
get { return enumCollection; }
set { enumCollection = value; NotifyPropertyChanged("EnumCollection"); }
}
...
EnumCollection.Add(TestEnum.One);
EnumCollection.Add(TestEnum.Two);
EnumCollection.Add(TestEnum.Three);
EnumInstance = TestEnum.Three;
Then we have a ComboBox:
<ComboBox Name="ComboBox" ItemsSource="{Binding EnumCollection}"
SelectedItem="{Binding EnumInstance}" />
If you run the application, then at this point the selected ComboBoxItem should read Three. Because the ComboBox.SelectedItem is data bound to the EnumInstance property, setting...:
EnumInstance = TestEnum.Two;
... is roughly the same as:
ComboBox.SelectedItem = TestEnum.Two;
Both of these would select the Two value in the ComboBox. However, note this example:
EnumInstance = TestEnum.None;
Setting either the EnumInstance or the ComboBox.SelectedItem property to TestEnum.None would have no effect in the UI because there is no TestEnum.None value in the data bound collection.
I apologise that my answer was descriptive enough, however, the reason why I haven't set my enum as a property as Sheridan has described below is that I need an extra string value in my combo which you can see is "Please Select" and unfortunately, I cannot put this in the enum.
But Sheridan's method and logic is the way to go if you want to do this.
However, for my problem, I simply just used
ComboBox.SelectedValue = Enum.Value.ToString();
Thanks

Categories

Resources