asem mokllati
asem mokllati

Reputation: 235

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

Upvotes: 0

Views: 134

Answers (1)

DrKoch
DrKoch

Reputation: 9772

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.

Upvotes: 1

Related Questions