0

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.

  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Yong Shun Apr 24 '21 at 05:38
  • I think you missed to create sStreamCmb. Btw: In most cases a setter for a ObservableCollection is useless and not what you want – Klamsi Apr 24 '21 at 06:39

1 Answers1

1

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.

ekke
  • 1,280
  • 7
  • 13