11 Replies - 4974 Views - Last Post: 10 June 2011 - 02:00 PM Rate Topic: -----

#1 nbarten  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 162
  • Joined: 30-April 07

Access form control from other class

Posted 09 June 2011 - 07:49 AM

Hi,

I'm sure this is asked many times before, but my search didn't find anything.

I have a form, Form1 called. In the form i have a textbox called textbox1 and a button. I have another class called Test.
In the class Test i have a function Go().

So, when i click the button in the form, i create a new object of class Test, called 'testobject'.

Then i do:

testobject.Go();



Now, in the Go method, which is located in the Test class, i want to set some text in the textbox of the form.

How can i do this?

Is This A Good Question/Topic? 0
  • +

Replies To: Access form control from other class

#2 Kilorn  Icon User is offline

  • XNArchitect
  • member icon



Reputation: 1356
  • View blog
  • Posts: 3,528
  • Joined: 03-May 10

Re: Access form control from other class

Posted 09 June 2011 - 08:04 AM

The easiest way is to just create a public property for the variable that you're trying to access.
public string Blah
{
    get { return textBox1.Text; }
    set { textBox1.Text = value; }
}


This post has been edited by Kilorn: 09 June 2011 - 08:05 AM

Was This Post Helpful? 1
  • +
  • -

#3 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4437
  • View blog
  • Posts: 7,713
  • Joined: 08-June 10

Re: Access form control from other class

Posted 09 June 2011 - 08:06 AM

*
POPULAR

Well, first things first: don't directly access UI components on other forms. I can't emphasize that enough. You technically can, but it's a horrible idea that leads to unmaintainable code.

Three options here.

1, Make the method "go" return a value, and use that to set the text box.

2, Put a property on your Test object, set the value in the Go method, and retrieve the value after you call Go.

3, create an event in your "test" class, and subscribe to it in the form's code. Here's a tutorial on passing values between forms, but it works equally well between classes (since forms are classes)

http://www.dreaminco...ny-other-forms/

You can find it and more like it in our Resource Thread.

The third is probably the best practice, but it's the most complex. It's really, really important to learn and understand events though, so you might as well start now.

This post has been edited by Curtis Rutland: 09 June 2011 - 08:07 AM

Was This Post Helpful? 5
  • +
  • -

#4 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5436
  • View blog
  • Posts: 11,666
  • Joined: 02-June 10

Re: Access form control from other class

Posted 09 June 2011 - 09:59 AM

Multiple FormA<->FormB links in the copy below


Standard resources, references and suggestions for new programmers.


I would recommend you start with "Hello World" just like the other million+ coders out there. Then work your way up to the more advanced tasks like this.

The problem with taking on large, complex tasks like this when you are new to coding is that
  • it will frustrate you to the point of quitting,
  • you don't know enough about coding to know where to start or in what direction to design your program
  • You risk learning via the 'Swiss cheese' method where you only learn certain bits and pieces for the one project but have huge holes in your education.


I am going to guess that you are trying to teach yourself C# without much guidance, a decent book or without knowing where to look. Sometimes just knowing where to look can make all the difference. Google is your friend.
Search with either "C#" or "MSDN" as the first word: "MSDN Picturebox", "C# Custom Events", "MSDN timer" etc.

But honestly, just typing away and seeing what pops up in Intellisense is going to make your self-education take 20 years. You can learn by trying to reverse engineer the language through banging on the keyboard experimentation - or you can learn by doing the tutorials and following a good "How to learn C#" book.

Free editions of Visual Studio 2010

May I suggest picking up a basic C# introductory book? There are so many great "How do I build my first application" tutorials on the web... There are dozens of "Learn C# in 21 days", "My first C# program" type books at your local book seller or even public library.

D.I.C. C# Resource page Start here
Intro to C# online tutorial then here...
C# control structures then here.
MSDN Beginner Developer video series
MSDN video on OOP principals, making classes, constructors, accessors and method overloading
MSDN Top guideline violations, know what to avoid before you do it.
Design patterns as diagrams

The tutorials below walk through making an application including inheritance, custom events and custom controls.
Bulding an application - Part 1
Building an application - Part 2
Quick and easy custom events
Passing values between forms/classes

Working with environmental variables
'Why do we use delegates?' thread

Debugging tutorial
Debugging tips
Great debugging tips
It still doesn't work, article

Build a Program Now! in Visual C# by Microsoft Press, ISBN 0-7356-2542-5
is a terrific book that has you build a Windows Forms application, a WPF app, a database application, your own web browser.

C# Cookbooks
Are a great place to get good code, broken down by need, written by coding professionals. You can use the code as-is, but take the time to actually study it. These professionals write in a certain style for a reason developed by years of experience and heartache.

Microsoft Visual Studio Tips, 251 ways to improve your productivity, Microsoft press, ISBN 0-7356-2640-5
Has many, many great, real-world tips that I use all the time.

Writing a text file is always one of the first things people want to do, in order to store data like high-scores, preferences and so on
Writing a text file tutorial.
Reading a text file tutorial.

And everyone always wants to connect to a database, right out of the gate so
Database tutorials right here on DIC

These are just good every-day references to put in your bookmarks.
MSDN C# Developers Center with tutorials
Welcome to Visual Studio

Have you seen the 500+ MSDN Code Samples? They spent a lot of time creating samples and demos. It seems a shame to not use them.

Let me also throw in a couple tips:
  • You have to program as if everything breaks, nothing works, the cyberworld is not perfect, the attached hardware is flakey, the network is slow and unreliable, the harddrive is about to fail, every method will return an error and every user will do their best to break your software. Confirm everything. Range check every value. Make no assumptions or presumptions.
  • Take the extra 3 seconds to rename your controls each time you drag them onto a form. The default names of button1, button2... button54 aren't very helpful. If you rename them right away to something like btnOk, btnCancel, btnSend etc. it helps tremendously when you make the methods for them because they are named after the button by the designer.
    btnSend_Click(object sender, eventargs e) is a lot easier to maintain than button1_click(object sender, eventargs e)
  • You aren't paying for variable names by the byte. So instead of variables names of a, b, c go ahead and use meaningful names like Index, TimeOut, Row, Column and so on. You should avoid 'T' for the timer. Amongst other things 'T' is commonly used throughout C# for Type and this will lead to problems. There are naming guidelines you should follow so your code confirms to industry standards. It makes life much easier on everyone around you, including those of us here to help. If you start using the standards from the beginning you don't have to retrain yourself later.
  • Try to avoid having work actually take place in GUI control event handlers. It is usually better to have the GUI handler call other methods so those methods can be reused and make the code more readible.
    btnSave(object sender, eventargs e)
    {
        SavePreferences();
    }
    
    SaveMenuItem(object sender, eventargs e)
    {
        SavePreferences();
    }
    
    SaveContextMenu(object sender, eventargs e)
    {
        SavePreferences();
    }
    
    Form1_Closing(object sender, eventargs e)
    {
        if (IsDirty) SavePreferences();
    }
    

Was This Post Helpful? 1
  • +
  • -

#5 nbarten  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 162
  • Joined: 30-April 07

Re: Access form control from other class

Posted 09 June 2011 - 10:54 AM

tlhIn`toq, although you are very hulpful, which i appreciate, i'm not a beginner in programming ;) It's just that i don't know all the concepts of C# just yet.

Let me explain my situation a bit more clearly. My first post was of course just an example to make the question more logical to explain, and for you easier to answer.

My goal is to create a little chat server... i know there is a tutorial, but i like to code the whole thing myself, i'll only ask questions if i really don't know how to do something.

What i had in mind was this: I have the class which contain the GUI (FormMain i've called it), but i don't want the code for the sockets and such there... only events for the controls (buttons, etc).

So i made a static class 'Controller', which begins to listen for incoming connections when the 'Listen' function is called. So i have in my click event of my button this code:

Controller.Listen();



Well, then the controller begins to listen and when a connections comes in, a new object of class 'Connection' is made, etc.

However, when the event rises for a new connection, i want this of course to be logged in the GUI (FormMain). Because it's a static class and it's not in the FormMain scope, i see no way to access the textfield on FormMain.

So i hope you understand my problem now ;)
Was This Post Helpful? 0
  • +
  • -

#6 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4437
  • View blog
  • Posts: 7,713
  • Joined: 08-June 10

Re: Access form control from other class

Posted 09 June 2011 - 11:12 AM

Well then, events are the answer. Again, don't directly access GUI components from another class/form, that's bad design.

Add some events to your class, and have your form subscribe to them. Here's an excellent writeup on publishing your own events:

http://msdn.microsof...y/w369ty8x.aspx

Basically, your Controller class is going to broadcast that something has happened. Anyone that wants to listen can. In your case, your main form will be listening, and will respond appropriately. This allows for loose coupling, meaning that your class isn't bound to your form in any meaningful way, so you could completely replace the GUI without changing the way the class itself is configured.
Was This Post Helpful? 1
  • +
  • -

#7 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5436
  • View blog
  • Posts: 11,666
  • Joined: 02-June 10

Re: Access form control from other class

Posted 09 June 2011 - 12:45 PM

View Postnbarten, on 09 June 2011 - 11:54 AM, said:

tlhIn`toq, although you are very hulpful, which i appreciate, i'm not a beginner in programming ;) It's just that i don't know all the concepts of C# just yet.

{...}

However, when the event rises for a new connection, i want this of course to be logged in the GUI (FormMain). Because it's a static class and it's not in the FormMain scope, i see no way to access the textfield on FormMain.

So i hope you understand my problem now ;)


These links from the earlier, more complete post, are something I would highly recommend you work through, then come back to your chat server project. They are aimed directly at the concepts you are unfamiliar with: Parent form makes a couple more classes, then subscribes to the event they throw and so on. It doesn't matter that the tutorials make virtual keyboards and react to their events, and your server makes connects and you react to those events. It's exactly the same thing.

I would say stop the chat server... do the tutorials... return to the chat server better armed.

The tutorials below walk through making an application including inheritance, custom events and custom controls.
Bulding an application - Part 1
Building an application - Part 2
Quick and easy custom events
Passing values between forms/classes
Was This Post Helpful? 1
  • +
  • -

#8 nbarten  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 162
  • Joined: 30-April 07

Re: Access form control from other class

Posted 09 June 2011 - 01:48 PM

@Curtis: Thank you, this is exactly what i need! I used the msdn example in my project (just fast for testing) and it worked, although it needed a few tweaks because i use a static class:

* static event (public static event EventHandler<CustomEventArgs> RaiseCustomEvent;)
* 'private static void OnRaiseCustomEvent' instead of 'protected virtual'...
* 'handler(null, e);' instead of 'handler(this, e);' -> which is also logical



@tlhIn`toq (what a name!): Thank you, i'll certainly look into it, especially part2 (although i need part1 for it too ;) )

Btw, i know this is off-topic... but i saw in part2 of your tutorial that you changed the font and color and such of a textbox to a rather cool one... do you maybe also know how to be able to edit the whole GUI? Like the window/frame, etc.
Was This Post Helpful? 0
  • +
  • -

#9 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5436
  • View blog
  • Posts: 11,666
  • Joined: 02-June 10

Re: Access form control from other class

Posted 10 June 2011 - 06:32 AM

View Postnbarten, on 09 June 2011 - 02:48 PM, said:

Btw, i know this is off-topic... but i saw in part2 of your tutorial that you changed the font and color and such of a textbox to a rather cool one... do you maybe also know how to be able to edit the whole GUI? Like the window/frame, etc.


One way: You make every form borderless and handle all the drawing yourself. You draw your own titlebar on your form including the caption, minimize/maximize/close widgets, borders and so on.

There are third party framework/component makers out there that have made themed components. You buy their parts and use them as you would the MS parts. So instead of a
System.Forms.Form you use
ThirdParty.Forms.Form

You of course could do the same thing.
Make a RedThemedButton that inherits from Button, override the ON_PAINT to do your custom themed drawing.
Repeat with all the other controls.
Now you can use your own themed controls from the toolbox in place of the MS ones.

You can either do that or some people do it all in photoshop and use images.

Images can be prettier and require less GDI+ understanding, but can bloat your application because it's a lot of resources. Then you are still left with a lot of computation because you make a graphic for the upperleft corner, the left edge, the lower right... you then paint in the UL, repeat the left edge down the side, then the LL, then repeat the bottom edge, then the LR, the repeat the right edge up the other side, then UR... etc. You can see where that is going.
Was This Post Helpful? 1
  • +
  • -

#10 nbarten  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 162
  • Joined: 30-April 07

Re: Access form control from other class

Posted 10 June 2011 - 08:09 AM

View PosttlhIn`toq, on 10 June 2011 - 07:32 AM, said:

You of course could do the same thing.
Make a RedThemedButton that inherits from Button, override the ON_PAINT to do your custom themed drawing.
Repeat with all the other controls.
Now you can use your own themed controls from the toolbox in place of the MS ones.


Thank you very much, this looks indeed the best option.. with the 'ON_PAINT' -> is this still C# you are talking about or is it C++ or something? Because you write it in capital...

It was always bothering me, it's nice to make applications with C#, but the looks were always the same. I've indeed tried some 3rd party components (free ones), but creating my own is ultimately my goal (well when my knowledge of C# is good enough).

Again, thank you very much, you explain stuff very clearly.
Was This Post Helpful? 0
  • +
  • -

#11 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4437
  • View blog
  • Posts: 7,713
  • Joined: 08-June 10

Re: Access form control from other class

Posted 10 June 2011 - 08:15 AM

Quote

but the looks were always the same


That's the goal. A unified, consistent UI. Custom is OK every now and then, but if everyone invents their own UIs, then there's no consistency, and you have to re-learn everything for every different application you have.

For example, you can assume that, if there's a program menu, it'll be at the top, aligned left. And if there's a save feature, it'll be in the file menu. And you can assume that the file menu looks like every other file menu, so it's easy to spot.

If you want truly and easily malleable UIs, give WPF a try. No overriding paint methods or any garbage like that. You can re-template any control you want.
Was This Post Helpful? 1
  • +
  • -

#12 nbarten  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 162
  • Joined: 30-April 07

Re: Access form control from other class

Posted 10 June 2011 - 02:00 PM

View PostCurtis Rutland, on 10 June 2011 - 09:15 AM, said:

If you want truly and easily malleable UIs, give WPF a try. No overriding paint methods or any garbage like that. You can re-template any control you want.


Thank you, i'll give it a try.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1