locked
Default Value In WPF Combobox RRS feed

  • Question

  • I am teaching myself VB.NET as I convert a personal Access VBA project.

    I have a form with a WPF Listview, ListView1, that is filtered by a Combobox, ComboBox1.  My Combobox is defined in XAML:

    <ComboBox Name="ComboBox1" HorizontalAlignment="Left" 
    Margin="150,260,0,0" VerticalAlignment="Top" Width="250" 
    IsSynchronizedWithCurrentItem="True" 
    ItemsSource="{Binding Path = Advisors1}" IsTextSearchEnabled="True" 
    SelectionChanged="ComboBox1_SelectionChanged" 
    SelectedValue="{Binding Path=Advisors}">
    In VB.NET, I setup the combo box and set it's SelectedValue property to _RetCB1 which contains the "aInitials" the Listview is filtered on:
            myCBAdapter1 = New OleDbDataAdapter(qryCmd)
            myCBAdapter1.Fill(myCBDataSet1, "Advisors1")
    
            ComboBox1.DataContext = myCBDataSet1
            ComboBox1.DisplayMemberPath = "aSubscription"
            ComboBox1.SelectedValuePath = "aInitials"
            ComboBox1.SelectedValue = _RetCB1

    Everything works great, almost.  When the form is loaded, the value of the Combobox is set to _RetCB1, which contains, "TM".  The Listview gets filtered based on "TM".  So far, so good.

    The only problem is that when the form is loaded, nothing is displayed on the surface of the Combobox to let the user know what value it contains.

    What do I need to do to get the corresponding "aSubscription" to show on the outside of the Combobox when the form is loaded?

    TIA...Chuck

    Monday, March 12, 2018 4:41 AM

Answers

  • Hi ChazzFX,

    You bind in XAML, I suggest you to define one class firstly, then define one list to populate data that you get from database.

    Person class

     class Person:INotifyPropertyChanged
        {
            private Int32 _Id;
            public Int32 Id
            {
                get
                {
                    return _Id;
                }
                set
                {
                    _Id = value;
                    NotifyPropertychanged("Id");
                }
            }
            private string _Name;
            public string Name
            {
                get
                {
                    return _Name;
                }
                set
                {
                    _Name = value;
                    NotifyPropertychanged("Name");
                }
            }
            public event PropertyChangedEventHandler PropertyChanged;
            private void NotifyPropertychanged(string propertyName)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                }
            }
    
    
    
    
        }

    PersonViewModel class

    class PersonViewModel:INotifyPropertyChanged 
        {
            private ObservableCollection<Person> _persons;
    
            public ObservableCollection<Person> Persons
            {
                get {
                    return _persons;
                }
                set {
                    _persons = value;
                    NotifyPropertychanged("_persons");
    
                }
            }
    
    
            private Person _sperson;
            public Person SPerson
            {
                get { return _sperson; }
                set
                {
                    _sperson = value;
                    NotifyPropertychanged("_sperson");
                }
            }
    
    
            public event PropertyChangedEventHandler PropertyChanged;
            private void NotifyPropertychanged(string propertyName)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                }
            }
    
            public PersonViewModel(DataTable dt)
            {
                Persons = new ObservableCollection<Person>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Person p = new Person();
                    p.Id = Convert.ToInt32(dt.Rows[i]["Id"]);
                    p.Name = dt.Rows[i]["Name"].ToString();                            
                    Persons.Add(p);
                }
    
    
            }
    
        }   

    .xaml

    <ComboBox Name="combobox2" HorizontalAlignment="Center" VerticalAlignment="Center" Width="250" DisplayMemberPath="Name" SelectedValuePath="Id" ItemsSource="{Binding Path=Persons}" SelectedItem="{Binding Path=Sperson}" SelectionChanged="combobox2_SelectionChanged"/>

    .xaml.cs

     DataSet ds = new DataSet();
            public Window4()
            {
                InitializeComponent();
                BindComboBox(ComboBox1);
                this.DataContext = new PersonViewModel(ds.Tables[0]);
            }
    
            public void BindComboBox(ComboBox comboBoxName)
            {
                string str = @"Data Source=(LOCALDB)\MSSQLLOCALDB;Initial Catalog=Testdb;Integrated Security=True";
                SqlConnection conn = new SqlConnection(str);
                SqlDataAdapter da = new SqlDataAdapter("Select Id, Name from T_users ", conn);
                
                da.Fill(ds, "tbl");
                
            }
    

    Best Regards,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Proposed as answer by Bob Ding Thursday, March 15, 2018 2:59 AM
    • Marked as answer by ChazzFX Friday, March 16, 2018 1:23 PM
    Tuesday, March 13, 2018 3:18 AM

All replies

  • Hi ChazzFX,

    Since this forum is discussing and asking questions about the Visual Basic programming language, IDE, libraries, samples, and tool, and your issue is more related to WPF, I will move this thread to the more related forum.

    Thanks for your understanding and support.


    Best Regards,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, March 12, 2018 9:16 AM
  • Hi ChazzFx,

    According to your description and code, you have get one datatable and want to  bind this datatable to combobox, if you want to bind in code behind, you can take a look the following code:

    public Window4()
            {
                InitializeComponent();
                BindComboBox(ComboBox1);
            }
    
            public void BindComboBox(ComboBox comboBoxName)
            {
                string str = @"Data Source=(LOCALDB)\MSSQLLOCALDB;Initial Catalog=Testdb;Integrated Security=True";
                SqlConnection conn = new SqlConnection(str);
                SqlDataAdapter da = new SqlDataAdapter("Select Id, Name from T_users ", conn);
                DataSet ds = new DataSet();
                da.Fill(ds, "tbl");
                comboBoxName.ItemsSource = ds.Tables[0].DefaultView;
                
                comboBoxName.DisplayMemberPath = ds.Tables[0].Columns["Name"].ToString();
                comboBoxName.SelectedValuePath = ds.Tables[0].Columns["Id"].ToString();
            }
    

    You don't need to bind in XAML, if you want to bind in XAML, you can use MVVM, there are many example about this, please refer to:

    https://www.c-sharpcorner.com/article/explain-combo-box-binding-in-mvvm-wpf/

    Best Regards,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, March 12, 2018 9:23 AM
  • Cherry,

    Thanks for taking the time to reply.  I see I was trying to bind the ComboBox both in code and in XAML.

    So I pulled the binding out of XAML and followed your example.  But as soon as I populated the ItemsSource property, the ComboBox SelectionChanged event would fire off, before I had a chance to populate the SelectedValue Property, which caused the query to fail that was trying to populate the ListView control.

    Then I followed your reference to the example of binding in XAML.  The ListView populated beautifully, but the ComboBox is empty.  Here's my XAML for the ComboBox:

            <ComboBox x:Name="ComboBox1" 
                      HorizontalAlignment="Left" 
                      Margin="150,510,0,0" 
                      VerticalAlignment="Top" 
                      Width="250" 
                      IsSynchronizedWithCurrentItem="True" 
                      SelectionChanged="ComboBox1_SelectionChanged"
                      ItemsSource="{Binding Path=Advisors1}"
                      SelectedItem="{Binding Path=aInitials}"
                      DisplayMemberPath="aSubscription"/>
    And here is my code:
            qryCmd.CommandType = CommandType.Text
            qryCmd.CommandText = "SELECT aSubscription,aInitials FROM tAdvisors ORDER BY aSubscription"
            qryCmd.Connection = conn
    
            '   conn.Open()
            myCBAdapter1 = New OleDbDataAdapter(qryCmd)
            myCBAdapter1.Fill(myCBDataSet1, "Advisors1")
    
            '        ComboBox1.ItemsSource = "Advisors1"
            '        ComboBox1.DisplayMemberPath = "aSubscription"
            '        ComboBox1.SelectedValuePath = "aInitials"
            Select Case _Portfolio
                Case "Retirement"
                    ComboBox1.SelectedValue = _RetCB1
                Case "Investment"
                    ComboBox1.SelectedValue = _InvCB1
                Case "Resource"
                    ComboBox1.SelectedValue = _ResCB1
            End Select
    
            myCBDataSet1.Dispose()
            myCBAdapter1.Dispose()
            qryCmd.Dispose()
    Any help you could provide would be appreciated...Chuck
    Tuesday, March 13, 2018 12:04 AM
  • Hi ChazzFX,

    You bind in XAML, I suggest you to define one class firstly, then define one list to populate data that you get from database.

    Person class

     class Person:INotifyPropertyChanged
        {
            private Int32 _Id;
            public Int32 Id
            {
                get
                {
                    return _Id;
                }
                set
                {
                    _Id = value;
                    NotifyPropertychanged("Id");
                }
            }
            private string _Name;
            public string Name
            {
                get
                {
                    return _Name;
                }
                set
                {
                    _Name = value;
                    NotifyPropertychanged("Name");
                }
            }
            public event PropertyChangedEventHandler PropertyChanged;
            private void NotifyPropertychanged(string propertyName)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                }
            }
    
    
    
    
        }

    PersonViewModel class

    class PersonViewModel:INotifyPropertyChanged 
        {
            private ObservableCollection<Person> _persons;
    
            public ObservableCollection<Person> Persons
            {
                get {
                    return _persons;
                }
                set {
                    _persons = value;
                    NotifyPropertychanged("_persons");
    
                }
            }
    
    
            private Person _sperson;
            public Person SPerson
            {
                get { return _sperson; }
                set
                {
                    _sperson = value;
                    NotifyPropertychanged("_sperson");
                }
            }
    
    
            public event PropertyChangedEventHandler PropertyChanged;
            private void NotifyPropertychanged(string propertyName)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                }
            }
    
            public PersonViewModel(DataTable dt)
            {
                Persons = new ObservableCollection<Person>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Person p = new Person();
                    p.Id = Convert.ToInt32(dt.Rows[i]["Id"]);
                    p.Name = dt.Rows[i]["Name"].ToString();                            
                    Persons.Add(p);
                }
    
    
            }
    
        }   

    .xaml

    <ComboBox Name="combobox2" HorizontalAlignment="Center" VerticalAlignment="Center" Width="250" DisplayMemberPath="Name" SelectedValuePath="Id" ItemsSource="{Binding Path=Persons}" SelectedItem="{Binding Path=Sperson}" SelectionChanged="combobox2_SelectionChanged"/>

    .xaml.cs

     DataSet ds = new DataSet();
            public Window4()
            {
                InitializeComponent();
                BindComboBox(ComboBox1);
                this.DataContext = new PersonViewModel(ds.Tables[0]);
            }
    
            public void BindComboBox(ComboBox comboBoxName)
            {
                string str = @"Data Source=(LOCALDB)\MSSQLLOCALDB;Initial Catalog=Testdb;Integrated Security=True";
                SqlConnection conn = new SqlConnection(str);
                SqlDataAdapter da = new SqlDataAdapter("Select Id, Name from T_users ", conn);
                
                da.Fill(ds, "tbl");
                
            }
    

    Best Regards,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Proposed as answer by Bob Ding Thursday, March 15, 2018 2:59 AM
    • Marked as answer by ChazzFX Friday, March 16, 2018 1:23 PM
    Tuesday, March 13, 2018 3:18 AM
  • Cherry,

    It took me a while to get your C# code translated to VB.net...but it's working now...Thanks.

    Friday, March 16, 2018 12:39 PM