How to Set the Selected Item in a Combobox to Match My String Using C#

ComboBox Selected Value - value that matches string

It solely depends on the actual ItemsSource you use with the ComboBox control.

If you set ComboBox1.ItemsSource = productsList; each item is of type Products (I would suggest to rename this to Product because it is confusing as the instance represents one single product, not multiple) and you must set SelectedItem to the product you want to select:

ComboBox1.SelectedItem = productsList[2]; //select the third item

You can also set the index that should be selected:

ComboBox1.SelectedIndex = 2; //select the third item
Why your approaches did not work

First approach

ComboBox1.SelectedItem = productList[0].ProductName.ToString();

Here you are setting SelectedItem to the ProductName which is a property of the Products item, but ComboBox is bound to a list of Products, it doesn't compare individual properties.

Second and third approach

ComboBox1.SelectedItem = ComboBox.SelectedItem.Where(
ComboBox => ComboBox.SelectedItem == productList[0].ProductName.ToString());
//and
ComboBox1.SelectedItem = DB_SelectorList.Where(
DB_SelectorList => DB_SelectorList.ProductName == productList[0].ProductName.ToString());

These two are closer, but not yet the full solution. The Where method is a LINQ extension method that returns IEnumerable<T> in this case IEnumerable<Products>. The reason is that Where may return multiple results. If you wanted to make this work, you would have to append .FirstOrDefault() before the semicolon to take just the first result for example. In any case, your goal is to set the SelectedItem property to an instance of a single "Products" (again, the name would be better as Product :-) )

The solution you can use is:

SelectedItem = listBoundToComboBox.FirstOrDefault( p => some condition );

set ComboBox selected item by Key not by value c#

You need to set the ValueMember property so the ComboBox knows what property to deal with when SelectedValue is being used. By default the ValueMember will be empty. So when you set the SelectedValue, the ComboBox does not know what you want to set.

this.comboBox1.ValueMember = "Key";

Normally, you would also set the DisplayMember property:

this.comboBox1.DisplayMember = "Value";

If you do not set it, it will just call ToString() on the object and display that. In your case the ToString() returns the Value.

how can i get the index of item whose key = 3 ?

If you want the item whose key is 3, why do you need to get it from the combobox? You can just get it from the collection the combobox is bound to:

For example, imagine this:

var items = new List<ComboItem> { new ComboItem(1, "One"),
new ComboItem( 2, "Two") };

this.comboBox1.DataSource = items;
this.comboBox1.DisplayMember = "Value";
this.comboBox1.ValueMember = "Key";

this.comboBox1.SelectedValue = 2;

If I need the item whose key is 2, then this will achieve that:

// Use Single if you are not expecting a null
// Use Where if you are expecting many items
var itemWithKey2 = items.SingleOrDefault(x => x.Key == 2);

How to set Selected item of ComboBox in C# Windows Forms?

You can get your item index by the .Items.IndexOf() method. Try this:

comboBox1.SelectedIndex = comboBox1.Items.IndexOf(gridView1.GetFocusedRowCellValue("vVendor"));

You don't need to iterate.

You can find more information in Stack Overflow question How do I set the selected item in a comboBox to match my string using C#?.

How to set the selected value of a combobox to a string value

Get rid of SelectedIndex="0" in your combo definition and try this:

 <ComboBox x:Name="cmbMyCmb" SelectedValuePath="Content" SelectionChanged="cmbMyCmb_SelectionChanged" Margin="99,104,117.4,157.8">
<ComboBoxItem Content="Please Select"/>
<ComboBoxItem Content="Item 1"/>
<ComboBoxItem Content="Item 2"/>
<ComboBoxItem Content="Item 3"/>
</ComboBox>

Code behind:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
//get item from database here
string itemFromDatabase = "Item 2";

cmbMyCmb.SelectedValue = itemFromDatabase;
}

enter image description here

Note I'm doing it in the Loaded event as a sample on how to change. If you do it in SelectionChanged event, the result is that whatever the user selects, your code behind is going to put it back to whatever value you want, which doesn't make sense.

C# - How do I set the selected item in a combobox by comparing my int value?

Use display and value memeber

Create custom class like this:

class MyCustomClass
{
//important to have get set part
public _int { get; set; }
public _string { get; set; }
}

now load data you want to display inside List<MyCustomClass>() and then bind that list to combobox and set it's display and value member like this:

myComboBox.DisplayMember = "_string";
myComboBox.ValueMember = "_int";
myComboBox.DataSource = myList; //this is List<MyCustomClass>

Now simply use myComboBox.SelectedValue = valueYouWant

IMPORTANT!!!

Declare displayMember and valueMember before binding datasource to combobox because of perfomance. Search internet for more info.

Set combobox selected index/item according to a condition

Figured it out :

            comboBox9.Items.Clear();
HashSet<string> distinct = new HashSet<string>();


foreach (_Excel.Range cell in range.Cells)
{
string value = (cell.Value2).ToString();

if (distinct.Add(value))
comboBox9.Items.Add(value);
}

if (comboBox9.Items.Count > 1)
{
foreach (string item in comboBox9.Items)
{
if (278 * Variables.m3h / (Math.Pow(int.Parse(item) / 2, 2) *
3.14) < Variables.maxvelocity)
{
comboBox9.SelectedIndex = comboBox9.Items.IndexOf(item);
break;
}
}
}
else
{
comboBox9.SelectedIndex = -1;
}

C# Winforms - setting combobox selected value

As described in the SelectedValue property documentation:

Property Value

An object containing the value of the member of the data source specified by the ValueMember property.

Remarks

If a property is not specified in ValueMember, SelectedValue returns the results of the ToString method of the object.

To get the desired behavior, you need to expose Name and Value as public properties of your Item class and utilize the DataSource, ValueMember and DisplayMember properties of the control:

// Content item for the combo box
private class Item
{
public string Name { get; private set; }
public int Value { get; private set; }
private Item(string _name, int _value)
{
Name = _name; Value = _value;
}
}

and the sample usage:

// Build a list with items
var items = new List<Item>();
// For example get from database continentals.
var gets = _connection.Continentals;
items.Add(new Item("--- Select a continental. ---", 0));
foreach (var get in gets)
{
items.Add(new Item(get.name.Length > 40 ? get.name.Substring(0, 37) + "..." : get.name, Convert.ToInt32(get.id)));
}
// Bind combobox list to the items
comboBox1.DisplayMember = "Name"; // will display Name property
comboBox1.ValueMember = "Value"; // will select Value property
comboBox1.DataSource = item; // assign list (will populate comboBox1.Items)

// Will select Africa
comboBox1.SelectedValue = 3;


Related Topics



Leave a reply



Submit