0

Can someone help me why Im getting NullReferenceException? I have a Filter function and want to Clear the items of a CheckBox before gettin new Items.

 if(comboboxSearch.Items != null)
 {
     comboboxSearch.Items.Clear();
 }
 LoadColumns();

I get Error in (if(comboboxSearch.Items != null) And an Error in LoadColumns:

try
        {
            connection = new MySqlConnection(conf.connection_string);
            if(this.OpenConnection() == true)
            {
                using (var schemaCommand = new MySqlCommand(columns_sql, connection))
                {
                    using (var reader = schemaCommand.ExecuteReader(CommandBehavior.SchemaOnly))
                    {
                        schema = reader.GetSchemaTable();
                    }
                }
                foreach (DataRow col in schema.Rows)
                {
                   comboboxSearch.Items.Add(UppercaseFirst(col.Field<String>("ColumnName")));  
                }
            }
            this.CloseConnection();
        }
        catch(MySqlException ex)
        {
            MessageBox.Show(ex.Message);
        }

At comboboxSearch.Items.Add(UppercaseFirst(col.Field<String>("ColumnName")));

In another Code the foreach works without if null check too. I dont Understand why I get this Error now because i check if it's null..

O Jean
  • 105
  • 9
  • 8
    `comboboxSearch` null perhaps? – Patrick Hofman Mar 21 '17 at 10:59
  • get vs2017, upgrade to .net 4.6.2 and you will get exactly what is null and why :) – zaitsman Mar 21 '17 at 11:02
  • I have no idea.. I read the topic and i dont think so it's duplicate. I can't find why it could be null.. And the thing is that I already check if it's null but i still get the Error. @PatrickHofman this works I guess. But the LoadColumns method don't work if i check if comboboxSearch is null. – O Jean Mar 21 '17 at 11:13
  • No, you are checking if the Items property is null. – Patrick Hofman Mar 21 '17 at 11:21
  • Yea that's why I changed it to what you said. But I also get an Error at `foreach (DataRow col in schema.Rows) { comboboxSearch.Items.Add(UppercaseFirst(col.Field("ColumnName")));}` And If I check if this is null to, it still gives me the Error. And I don't understand why comboboxSearch is null. – O Jean Mar 21 '17 at 11:30
  • Still need help, my C# Experience is not that good. I don't understand why my combobox is null. In another WPF window, the combobox.Items.Add works fine and it's the same. So why not here? – O Jean Mar 21 '17 at 13:33
  • I fixed it. I load the functions in Windows_Loaded Event. Then it works without "if null" etc. – O Jean Mar 21 '17 at 15:06

0 Answers0