tags:

views:

327

answers:

4
    public void CheckUnusedTabs(string strTabToRemove)
    { 
        TabPage tp = TaskBarRef.tabControl1.TabPages[strTabToRemove];
        tp.Controls.Remove(this);
        TaskBarRef.tabControl1.TabPages.Remove(tp);
    }

I am trying to close a tab in the tabcontrol of windows application using the above code and i encountered the error : cross thread operation not valid. How to solve this ?

+1  A: 

When using threads and UI controls, in winforms, you need to use InvokeRequired to make changes to the controls.

EDIT.

added an example.

Form, with button and label.

try

private void button2_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(UpdateProcess);
            thread.Start();
        }

        private void SetLabelText(string val)
        {
            label1.Text = val;
        }
        delegate void m_SetLabel(string val);

        private void UpdateProcess()
        {
            int i = 0;

            while (true)
            {
                if (label1.InvokeRequired)
                {
                    m_SetLabel setLabel = SetLabelText;
                    Invoke(setLabel, i.ToString());
                }
                else
                    label1.Text = i.ToString();
                i++;
                Thread.Sleep(500);
            }
        }
astander
@astander, can u tell me how ?
Anuya
@astander i tried adding ...if(TaskBarRef.tabControl1.incokerequired)
Anuya
check the answer, added an example.
astander
A: 

call using invoke, because you're accessing the GUI thread using another thread

 this.Invoke((MethodInvoker)delegate() {CheckUnusedTabs(""); });
Mustafa A. Jabbar
+5  A: 

You can only make changes to WinForm controls from the master thread. You need to check whether InvokeRequired is true on the control and then Invoke the method as needed.

You can do something like this to make it work:

public void CheckUnusedTabs(string strTabToRemove)
{ 
    if (TaskBarRef.tabControl1.InvokeRequired)
    {
        TaskBarRef.tabControl1.Invoke(new Action<string>(CheckUnusedTabs), strTabToRemove);
        return;
    }      

    TabPage tp = TaskBarRef.tabControl1.TabPages[strTabToRemove];
    tp.Controls.Remove(this);
    TaskBarRef.tabControl1.TabPages.Remove(tp);
}
JDunkerley
A: 

set

checkillegalcrossthreadvalidation=false

maxy
CheckIllegalCrossThreadValidation is a safety check to prevent some versions of Windows from crashing when you try to do cross-thread UI updates. It's madness to turn it off.
Christian Hayter