简体   繁体   中英

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);
            }
        }
    }

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM