Gabriel Vieira
Gabriel Vieira

Reputation: 57

Getting error "Object reference not set to an instance of an object" populating comboBox dynamically created

Hi I'm trying to populate a dynamic created comboBox using data from a database, but it shows an exception (Object reference not set to an instance of an object). And I'm tired of looking. What is missing here? Thanks For all the help! (newbie here)

private void SetComboBoxItems()
    {
        foreach (Control control in panelMain.Controls)
        {
            ComboBox comboBox = control as ComboBox;
            try
            {
                using (MySqlConnection connection = new MySqlConnection(Properties.Settings.Default.connectionString))
                {
                    connection.Open();
                    MySqlCommand command = new MySqlCommand("SELECT * FROM home.data", connection);
                    MySqlDataReader dataReader = command.ExecuteReader();
                    while (dataReader.Read())
                    {
                        comboBox.Items.Add((string)dataReader["temp"]);
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }

Upvotes: 0

Views: 88

Answers (1)

Orbittman
Orbittman

Reputation: 336

Your question is a little vague but as a guess I'd say that you're iterating though all of the controls in panelMain.Controls and trying to cast them to ComboBox. Any that aren't ComboBox, I can't remember any off the top of my head, will be null. You don't check for null but still make the DB call that then fails when you try to set the items. I's suggest the following:

foreach (Control control in panelMain.Controls)
        {
            ComboBox comboBox = control as ComboBox;
            if(comboBox != null){
                try
                {

or

foreach (Control control in panelMain.Controls.Where(c => c is ComboBox))

Upvotes: 2

Related Questions