开发者

Calling form controls from a thread in C#

I 开发者_高级运维am stuck in a deep problem right now. Plz help me with this....

I created a FORM call it form1. It contains a textbox T1. I started it running... inside form1 there is a thread running which does some process P which is a member of a different CLASS call it class2. To run the process P, I need a value from textbox T1. HOW DO I DO THAT?

Let me tell you, what I tried already. I created instance of form1 in class2, and then tried to read textbox (T1) value. But that was empty, I figured out that reason.... rest, I tried with the property... Again failed...

PLZ help me with this. I am stuck since hours....


This is just an example to point you in the right direction. As mentioned in another answer you might have to Invoke to prevent cross-thread exceptions.

Inside your class named FORM add a method or property:

public string GetTextboxContent()
{
    return textbox.Text;
}

Change your class2 to something like this:

class class2
{
    private MyForm m_form;

    public class2(MyForm form)
    {
        m_form = form;
    }

    public void DoThreadStuff()
    {
        string value = m_form.GetTextboxContent();
    }
}

You said "I created instance of form1 in class2, and then tried to read textbox (T1) value. But that was empty": Don't create a new instance: Pass the existing instance to class2!


    Assuming Class1 is the class which does some process in thread. Create the property which corresponds to type of your main form. In this case, its called Form1. 



     class Class1
        {
    //his is the property
            public Form1 MyMainForm { get; set; }

            public  void    ShowText()
            {

//here the control is accesses 
//((TextBox)MyMainForm.Controls.Find("textBox1",true)[0])
                MessageBox.Show(((TextBox)MyMainForm.Controls.Find("textBox1",true)[0]).Text);
            }
        }

    im assuming ShowText() method is called on new thread, when button is clicked.

     private void button1_Click(object sender, EventArgs e)
            {
    //craete instance of class1
                Class1 c = new Class1();
    //set the  property            
    c.MyMainForm = this;
    //start the method is new thread
                ThreadStart ts=new ThreadStart(c.ShowText);
                Thread t=new Thread(ts);
                t.Start();
            }


Try this..

You Class..

ClassText
{
   YourClass(String textVAlue)
   {
   }
 }

Your Form..

ClassText ct = new ClassText();
ct.YourClass(Textbox1.text);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜