Search code examples
c#mysqlwpfmvvmcombobox

How to load combobox drop-down list from database with multiple selection in wpf using mvvm


I'm trying to populate combobox drop-down list with data from the database. This should be loaded dynamically, on loading the window

View model

public class StdBasicVM
{
        private ObservableCollection<string> _sStreamCmb;
        public ObservableCollection<string> sStreamCmb
        {
            get { return _sStreamCmb; }
            set { if (_sStreamCmb != value) { _sStreamCmb = value; OnPropertyChanged("sStreamCmb"); } }
        }

        private void COMBOBOX()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["connscmag"].ConnectionString;
            using (var conn = new MySqlConnection(connectionString))
            {
                conn.Open();

                var query = "Select distinct entry FROM gidentifiers WHERE IDENTIFIER = 'STREAM' AND entry <> 'NULL'  ";
                using (var comm = new MySqlCommand(query, conn))
                {
                    using (var reader = comm.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            if (reader.HasRows)
                            {
                              sStreamCmb.Add(reader.GetString("entry").ToString());
                            }

                        }
                    }
                }


            }

        }

        public StdBasicVM()
        {
            COMBOBOX();
        }
}

Window

<ComboBox x:Name="txtStream" Grid.Row="9" Grid.Column="1" 
Text="{Binding sStream, Mode=TwoWay}" 
DisplayMemberPath="Name" 
ItemsSource="{Binding sStreamCmb}"/>

It generates an error on line sStreamCmb.Add(reader.GetString("entry").ToString()) object reference not set to an instance of an object.


Solution

  • In your code you're not initialising the combo box observable collection. Change this line:

    private ObservableCollection<string> _sStreamCmb;
    

    To this:

    private ObservableCollection<string> _sStreamCmb= new ObservableCollection<string>();
    

    And it should fix the issue. You can highlight when this happens by adding this line in your csproj file:

        <WarningsAsErrors>CS0649</WarningsAsErrors>
    

    This will treat situations like above as errors saving you having to find out at runtime.