How to access form elements from outside the form class

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • aatif
    New Member
    • Mar 2009
    • 28

    How to access form elements from outside the form class

    I want to change the text of a textfield of a c# form object, but from outside that class. How can I do it?
    By passing that form field as a reference? How can I pass a reference of that form or textfield to that function if I am running that function in a separate thread?

    Thanx
  • PRR
    Recognized Expert Contributor
    • Dec 2007
    • 750

    #2
    I would rather keep UI and logic separate.... its better that way....
    as for your question

    a. You can pass as parameter the control id which you intend to change
    Code:
    public void ChangeText(System.Windows.Forms.Button t)
           {
               t.Text = "Bytes";
           }
    
    Class my = new Class();           
    
                my.ChangeText(this.button1);
    b. Or you could use Controls.Find method ...or you can loop through the controls in your class method ... You should give the form object as input method ...

    Code:
    public void ChangeSomething(System.Windows.Forms.Form myForm)
           {
    
               System.Windows.Forms.Control[]  bb = myForm.Controls.Find("button1", true);
    
               foreach (System.Windows.Forms.Control c in bb)
               {
                   if (c.Name == "button1")
                   {
                       c.Text = "CCC";
                   }
               }
    
               //OR
    
               foreach (System.Windows.Forms.Control c in myForm.Controls)
               {
                   if (c.Name == "button1")
                   {
                       System.Windows.Forms.Button b = c as System.Windows.Forms.Button;
                       //b.Text = "Changed from class";
                   }
               }
           }
    In your form.cs on button click, you can call
    Code:
    Class my = new Class();
                my.ChangeSomething(this);

    Comment

    • aatif
      New Member
      • Mar 2009
      • 28

      #3
      How can I check that the control which I am looking for exists in the 'Controls' list? The foreach loop fails to search by name.

      Comment

      • tlhintoq
        Recognized Expert Specialist
        • Mar 2008
        • 3532

        #4
        When you make the control on the target form, give it a meaningful name that you can look for from the other class.

        Comment

        • Bassem
          Contributor
          • Dec 2008
          • 344

          #5
          Don't forget,
          If you're going to access a control from another thread than the one the control is created on, you'll face the cross-thread exception.
          Check it by using IsInvokeRequire d property!

          Comment

          • alexgm23
            New Member
            • Mar 2009
            • 6

            #6
            Use Delegates

            You can use a delegate to get access to a control that is in another thread:

            Code:
            // This is an extract from a server/client socket program
            
            delegate void SetTextCallback(String Text);
            
            private void SetText(String Text)
            {
            	if (textBox1.InvokeRequired)
            	{
            		SetTextCallback d = new SetTextCallback(SetText);
            		this.Invoke(d, new object[] { Text });
            	}
            	else
            	{
            		this.textBox1.Text = this.textBox1.Text + Text + "\r\n";
            	}
            }
            
            public void OnDisconnect(IAsyncResult asyn)
            {
            	((Socket)asyn.AsyncState).EndDisconnect(asyn);
            	SetText(clientSocket.RemoteEndPoint.ToString() + " has disconnected!");
            }
            I hope this helps!!

            Alex G.
            Last edited by PRR; Mar 16 '09, 04:37 AM. Reason: Removed email...

            Comment

            • aatif
              New Member
              • Mar 2009
              • 28

              #7
              Alex,
              Sorry I couldn't get it, do you have an example?

              Bassem,
              where is IsInvokeRequire d...?

              Comment

              • aatif
                New Member
                • Mar 2009
                • 28

                #8
                ok, I am done.

                Code:
                public void UpdateText()
                {
                    Control[] ctrlResponse = isoAgentForm.Controls.Find("textStatus", true);
                    if (!ctrlResponse[0].InvokeRequired)
                    {
                        ctrlResponse[0].Text = statusMsg;
                    }
                    else
                    {
                        ctrlResponse[0].Invoke(new ThreadStart(UpdateText));
                    }
                }
                I also changed the textfield from private to public.



                Any good suggestion?

                Comment

                • matasoy
                  New Member
                  • Oct 2012
                  • 1

                  #9
                  Most easy way is to change your element private to public on projects.cs

                  private System.Windows. Forms.Button button1;
                  private System.Windows. Forms.Button button2;
                  public System.Windows. Forms.Label label1;

                  Comment

                  Working...