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.
Related
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>
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.
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".
I am using WPF ComboBox,
I want to retrieve all the values from a ComboBox or a ComboBoxItem by using Index
var v = cmbSubject.Items.GetItemAt(0);
Here is the answer
var v = cmbSubject.Items.GetItemAt(0);
DataRowView dv = (DataRowView)v;
string strCmbItem = dv[1].ToString();
Something like that ?
List<var> Items = cmbSubject.Items;
Example XAML:
<ComboBox x:Name="myComboBox" SelectedIndex="0" >
<ComboBoxItem Content="Item one"></ComboBoxItem>
<ComboBoxItem Content="Item two"></ComboBoxItem>
<ComboBoxItem Content="Item three"></ComboBoxItem>
</ComboBox>
The ComboBox in this example has 3 items, these are ComboBoxItems. If you try to get the Content of a ComboBox you will need something like this:
String ContentOfItemOne = (myComboBox.Items[0] as ComboBoxItem).Content.ToString();
I hope it helps.
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);