locked
How to set a item as selected in a combobox Windows Store ?

    Question

  • hi experts. 

    I have a combobox that is loading a list. 
    How do I get the displayed value is set programmatically? 

    EX: When you open a page that will perform the update of the data, the combobox loaded and should come with the option that was previously saved already chosen.

    My code:

     private async Task FillFields()
            {
                string sError = string.Empty;
                try
                {
                    Contas conta = new Contas();
                    conta = await GetSelectedItem();
                    if (conta != null)
                    {
                        ControllerTiposDespesas ct = new ControllerTiposDespesas();
    
                        var item = ct.GetTipoDespesa(conta.IdDespesa); 
                        if (item != null)
                        {
                            CbTipo.SelectedItem = item;
                        }
                        txtValor.Text = conta.Valor.ToString("C");
                        dpDtVcto.SelectedDate = conta.DtVcto;
                        txtObser.Text = conta.Observacao;
    
                    }
                    conta = null;
                }
                catch (Exception ex)
                {
    
                    sError = string.Format("Ocorreu um erro ao preencher campos do flyout: {0}", ex.Message);
                }
                if (!string.IsNullOrEmpty(sError))
                {
                    MessageDialog msg = new MessageDialog(sError, "Erro");
                    await msg.ShowAsync();
                }
            }

    Sorry for my english


    Brian Souza - MCP Desenvolvedor C#.Net

    Friday, April 11, 2014 1:06 PM

Answers

  • Crate a project with name App1 in Visual Studio 2013 using default blank app template and replace code in MainPage.xaml and MainPage.xaml.cs with this:

    <Page
        x:Class="App1.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:App1"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d">
        <Page.Resources>
    
        </Page.Resources>
    
        <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
            <ComboBox x:Name="selectDepartment" Margin="10" Height="20" Width="100" DisplayMemberPath="Name"></ComboBox>
        </Grid>
    </Page>
    


    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Windows.UI.Xaml.Controls;
    
    // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
    
    namespace App1
    {
        public class Department
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Manager { get; set; }
        }
    
        /// <summary>
        /// An empty page that can be used on its own or navigated to within a Frame.
        /// </summary>
        public sealed partial class MainPage : Page
        {
            private Task<bool> loadDataTask;
    
            public MainPage()
            {
                this.InitializeComponent();
    
                loadDataTask = loadData();
            }
    
            private async Task<bool> loadData()
            {
                List<Department> departments = await getDepartments();
    
                selectDepartment.ItemsSource = departments;
    
                Department selectedDepartment = await getSelectedDetartment();
    
                //Option 1
                if (selectedDepartment != null && departments != null)
                {
                    Department department = (from d in departments where d.Id == selectedDepartment.Id select d).FirstOrDefault();
    
                    if (department != null)
                    {
                        selectDepartment.SelectedIndex = departments.IndexOf(department);
                    }
                    else
                    {
                        selectDepartment.SelectedIndex = -1;
                    }
                }
    
                //Option 2
                //if (selectedDepartment != null && departments != null)
                //{
                //    Department department = (from d in departments where d.Id == selectedDepartment.Id select d).FirstOrDefault();
    
                //    if (department != null)
                //    {
                //        selectDepartment.SelectedValue = department;
                //    }
                //    else
                //    {
                //        selectDepartment.SelectedValue = null;
                //    }
                //}
    
                //Option 3
                //if (selectedDepartment != null && departments != null)
                //{
                //    Department department = (from d in departments where d.Id == selectedDepartment.Id select d).FirstOrDefault();
    
                //    if (department != null)
                //    {
                //        selectDepartment.SelectedItem = selectDepartment.Items[departments.IndexOf(department)];
                //    }
                //    else
                //    {
                //        selectDepartment.SelectedItem = null;
                //    }
                //}
    
                return true;
            }
    
            /// <summary>
            /// This method is to simulate a Data Access call
            /// </summary>
            /// <returns></returns>
            private async Task<List<Department>> getDepartments()
            {
                List<Department> departments = new List<Department>();
    
                //Dummy wait to simulate data being read from service
                await Task.Delay(100);
    
                departments.Add(new Department() { Id = 1, Name = "Dept 1", Manager = "Manager 1" });
                departments.Add(new Department() { Id = 2, Name = "Dept 2", Manager = "Manager 2" });
                departments.Add(new Department() { Id = 3, Name = "Dept 3", Manager = "Manager 3" });
                departments.Add(new Department() { Id = 4, Name = "Dept 4", Manager = "Manager 4" });
                departments.Add(new Department() { Id = 5, Name = "Dept 5", Manager = "Manager 5" });
                departments.Add(new Department() { Id = 6, Name = "Dept 6", Manager = "Manager 6" });
                departments.Add(new Department() { Id = 7, Name = "Dept 7", Manager = "Manager 7" });
                departments.Add(new Department() { Id = 8, Name = "Dept 8", Manager = "Manager 8" });
                departments.Add(new Department() { Id = 9, Name = "Dept 9", Manager = "Manager 9" });
    
                return departments;
            }
    
            /// <summary>
            /// This method is to simulate a method to get selected department
            /// </summary>
            /// <returns></returns>
            private async Task<Department> getSelectedDetartment()
            {
                //Dummy wait to simulate data being read from service
                await Task.Delay(100);
    
                return (new Department() { Id = 5, Name = "Dept 5", Manager = "Manager 5" });
            }
        }
    }
    

    As Jamles suggested there are three options to do what you need, and my code shows you all of them.


    -- Vishal Kaushik --

    Please 'Mark as Answer' if my post answers your question and 'Vote as Helpful' if it helps you. Happy Coding!!!

    • Marked as answer by Brian Souza Tuesday, April 22, 2014 2:50 PM
    Sunday, April 20, 2014 10:31 AM

All replies

  • Hi Brain,

    For programmatically select the item/ get the selected items in combobox, use SelectedIndex or SelectedItem or SelectedValue  per your requirement.

    However I'm not able to understand your code, if you want to fix the issue, please give a more detail explanation what you have done and where you meet the problem.

    --James


    <THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
    Thanks
    MSDN Community Support

    Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

    Monday, April 14, 2014 6:39 AM
    Moderator
  • This is the part that has to do with my problem: 

      var item = ct.GetTipoDespesa (conta.IdDespesa); 
                         if (item! = null) 
                         {
                             CbTipo.SelectedItem = item; 
                         } 



    The GetTipoDespesa method returns an object of the same type that populates the ComboBox, then I try to set it filled the option you selected should come. No runtime error occurs, but also leaves the option selected.

    Brian Souza - MCP Desenvolvedor C#.Net

    Saturday, April 19, 2014 8:11 PM
  • Crate a project with name App1 in Visual Studio 2013 using default blank app template and replace code in MainPage.xaml and MainPage.xaml.cs with this:

    <Page
        x:Class="App1.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:App1"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d">
        <Page.Resources>
    
        </Page.Resources>
    
        <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
            <ComboBox x:Name="selectDepartment" Margin="10" Height="20" Width="100" DisplayMemberPath="Name"></ComboBox>
        </Grid>
    </Page>
    


    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Windows.UI.Xaml.Controls;
    
    // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
    
    namespace App1
    {
        public class Department
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Manager { get; set; }
        }
    
        /// <summary>
        /// An empty page that can be used on its own or navigated to within a Frame.
        /// </summary>
        public sealed partial class MainPage : Page
        {
            private Task<bool> loadDataTask;
    
            public MainPage()
            {
                this.InitializeComponent();
    
                loadDataTask = loadData();
            }
    
            private async Task<bool> loadData()
            {
                List<Department> departments = await getDepartments();
    
                selectDepartment.ItemsSource = departments;
    
                Department selectedDepartment = await getSelectedDetartment();
    
                //Option 1
                if (selectedDepartment != null && departments != null)
                {
                    Department department = (from d in departments where d.Id == selectedDepartment.Id select d).FirstOrDefault();
    
                    if (department != null)
                    {
                        selectDepartment.SelectedIndex = departments.IndexOf(department);
                    }
                    else
                    {
                        selectDepartment.SelectedIndex = -1;
                    }
                }
    
                //Option 2
                //if (selectedDepartment != null && departments != null)
                //{
                //    Department department = (from d in departments where d.Id == selectedDepartment.Id select d).FirstOrDefault();
    
                //    if (department != null)
                //    {
                //        selectDepartment.SelectedValue = department;
                //    }
                //    else
                //    {
                //        selectDepartment.SelectedValue = null;
                //    }
                //}
    
                //Option 3
                //if (selectedDepartment != null && departments != null)
                //{
                //    Department department = (from d in departments where d.Id == selectedDepartment.Id select d).FirstOrDefault();
    
                //    if (department != null)
                //    {
                //        selectDepartment.SelectedItem = selectDepartment.Items[departments.IndexOf(department)];
                //    }
                //    else
                //    {
                //        selectDepartment.SelectedItem = null;
                //    }
                //}
    
                return true;
            }
    
            /// <summary>
            /// This method is to simulate a Data Access call
            /// </summary>
            /// <returns></returns>
            private async Task<List<Department>> getDepartments()
            {
                List<Department> departments = new List<Department>();
    
                //Dummy wait to simulate data being read from service
                await Task.Delay(100);
    
                departments.Add(new Department() { Id = 1, Name = "Dept 1", Manager = "Manager 1" });
                departments.Add(new Department() { Id = 2, Name = "Dept 2", Manager = "Manager 2" });
                departments.Add(new Department() { Id = 3, Name = "Dept 3", Manager = "Manager 3" });
                departments.Add(new Department() { Id = 4, Name = "Dept 4", Manager = "Manager 4" });
                departments.Add(new Department() { Id = 5, Name = "Dept 5", Manager = "Manager 5" });
                departments.Add(new Department() { Id = 6, Name = "Dept 6", Manager = "Manager 6" });
                departments.Add(new Department() { Id = 7, Name = "Dept 7", Manager = "Manager 7" });
                departments.Add(new Department() { Id = 8, Name = "Dept 8", Manager = "Manager 8" });
                departments.Add(new Department() { Id = 9, Name = "Dept 9", Manager = "Manager 9" });
    
                return departments;
            }
    
            /// <summary>
            /// This method is to simulate a method to get selected department
            /// </summary>
            /// <returns></returns>
            private async Task<Department> getSelectedDetartment()
            {
                //Dummy wait to simulate data being read from service
                await Task.Delay(100);
    
                return (new Department() { Id = 5, Name = "Dept 5", Manager = "Manager 5" });
            }
        }
    }
    

    As Jamles suggested there are three options to do what you need, and my code shows you all of them.


    -- Vishal Kaushik --

    Please 'Mark as Answer' if my post answers your question and 'Vote as Helpful' if it helps you. Happy Coding!!!

    • Marked as answer by Brian Souza Tuesday, April 22, 2014 2:50 PM
    Sunday, April 20, 2014 10:31 AM