Search code examples
c#comboboxuwpselecteditemselectedvalue

ComboBox Selected Value - value that matches string


How to set SelectedValue or SelectedItem of ComboBox in C# UWP programmatically? I have a ComboBox binded to the list of strings and I want it to select automatically the string that matches string from other list.

ObservableCollection<Products> DB_Products = new ObservableCollection<Products>();
ReadAllProductsList dbproducts = new ReadAllProductsList();
DB_Products = dbproducts.GetAllProducts();
List<Products> productsList = new List<Products>();
productsList = DB_Products.ToList();

below unknown

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

or something like:

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

or:

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

Solution

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