简体   繁体   中英

combobox add items throw Exception “Specific cast is not valid”

Hi i have the following code to add some items into combobox When i do the code it in a thread i have the following exception "Specific cast is not valid" But when do it in main form thread there is no exception. any idea how to solve this?

        Control.CheckForIllegalCrossThreadCalls = false;

        //Auto Complete
        comboBox3.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
        comboBox3.AutoCompleteSource = AutoCompleteSource.ListItems;

        //no specific formatting
        comboBox3.FormattingEnabled = true;

        Thread th1 = new Thread(() =>
            {
                try
                {
                    //# Code Start

                    //Some Text 
                    String[] TicketStatus = new string[] { "a", "b", "c", "d", "e" };

                    //Throw Exception "Specific cast is not valid"
                    comboBox3.Items.AddRange(TicketStatus);

                    //# Code End
                }
                catch (Exception c) { MessageBox.Show(c.Message); }
            });
        th1.Start();

like this no Exception

  Control.CheckForIllegalCrossThreadCalls = false;

        //Auto Complete
        comboBox3.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
        comboBox3.AutoCompleteSource = AutoCompleteSource.ListItems;

        //no specific formatting
        comboBox3.FormattingEnabled = true;


        //# Code Start

        //Some Text 
        String[] TicketStatus = new string[] { "a", "b", "c", "d", "e" };

        //Throw Exception "Specific cast is not valid"
        comboBox3.Items.AddRange(TicketStatus);

        //# Code End

You can't access UI elements from a thread other than the UI thread.

You'll have to marshall the setter code back to the UI thread.

Use InvokeRequired to do so.

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