8 Replies - 24162 Views - Last Post: 25 June 2011 - 01:34 PM Rate Topic: -----

#1 farril   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 110
  • Joined: 04-March 09

Trying to change label from another class

Posted 25 June 2011 - 09:10 AM

Hi, i'm very new at coding (i say new, i did it for 3 years at university but still can't seem to grasp it easily)

I have a form (called Game) with a label, label1.

I run a class in another file, and if its successful i want to update the text in this label.

In my game.cs i have

    public partial class Game : Form
    {
        public void SetLabel(string newText)
        {
            Invoke(new Action(() => label1.Text = newText));
        }
}



And in another file (network.cs) i test if connection is successful, if it is, i want to update.

        public static void OnConnect(IAsyncResult result)
        {

            try
            {
                if (client.Connected)
                {
                 Game.SetLabel("connected");
                }
                else
                {
                   Game.SetLabel("not connected");
                }
            }
}



But i get this compile error,

Error	1	An object reference is required for the non-static field, method, or property 'Client.Game.SetLabel(string)'



I know its a simply error, and i'm trying to change the label the wrong way, but i've no clue how to fix it.

Is This A Good Question/Topic? 0
  • +

Replies To: Trying to change label from another class

#2 Jeff H   User is offline

  • D.I.C Regular

Reputation: 112
  • View blog
  • Posts: 308
  • Joined: 30-January 11

Re: Trying to change label from another class

Posted 25 June 2011 - 09:42 AM

What the error is saying is you need a instance of the form.


Game gme = new Game();
gme.SetLabel();

gme is a refernce to a actual Game object, but
I will stop here because there is a more important point.

Would it make sense every time a program connected to database or whatever it changed the label on a form.

To start off very simple would it make more since for OnConnect to return a value if it connected?

That way you are not coupling the form to the method, and by returning a bool you can do different things.

if (OnConnect)
label.Text = "connected"

if (Onconnect) is false
do this.....
Was This Post Helpful? 0
  • +
  • -

#3 Martyr2   User is offline

  • Programming Theoretician
  • member icon

Reputation: 5554
  • View blog
  • Posts: 14,560
  • Joined: 18-April 07

Re: Trying to change label from another class

Posted 25 June 2011 - 09:45 AM

You are trying to access the method through the class name "Game". You can only do this if SetLabel() was a static method. You need to create an instance of the Game object and call the method through that. Being that this is a different class, you need to pass your Game instance object to the other class (through a constructor or a property etc).

I know what I just said probably sounded pretty cryptic. Let me see if I can simplify this with a little code...

// Create an instance of Game first...
Game g = new Game();

// Now I can call SetLabel on the instance (this is the object reference it is talking about)
g.SetLabel("some text");



What you are trying to do is access that method as if it was static. Just like you would call Math.sqrt() without needing to create an instance of "Math" first.

So being in another class, how do you get access to this Game instance? You pass it to your class...

Game g = new Game();

MyOtherClass other = new MyOtherClass(g); //<--- Through its constructor

// Or

other.SetParent(g); //<--- Pass through a custom method you created for your class

// Or

other.variable = g; //<--- Set public variable of your class (not recommended)



Since your "MyOtherClass" is probably another form you can setup the property/custom method for the form and pass it in through that method. If the other class is not a form, you can use the property/custom method or public variable depending on your needs.

:)
Was This Post Helpful? 0
  • +
  • -

#4 farril   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 110
  • Joined: 04-March 09

Re: Trying to change label from another class

Posted 25 June 2011 - 10:17 AM

View PostJeff H, on 25 June 2011 - 10:42 AM, said:

What the error is saying is you need a instance of the form.


Game gme = new Game();
gme.SetLabel();

gme is a refernce to a actual Game object, but
I will stop here because there is a more important point.

Would it make sense every time a program connected to database or whatever it changed the label on a form.

To start off very simple would it make more since for OnConnect to return a value if it connected?

That way you are not coupling the form to the method, and by returning a bool you can do different things.

if (OnConnect)
label.Text = "connected"

if (Onconnect) is false
do this.....


Thanks for your help, i tried creating an instance but then i get the following error,

Invoke or BeginInvoke cannot be called on a control until the window handle has been created.



Unfortunately i don't think i can use a return value as i have a lot more code in that class, i just took everything out.
Was This Post Helpful? 0
  • +
  • -

#5 eclipsed4utoo   User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1536
  • View blog
  • Posts: 5,972
  • Joined: 21-March 08

Re: Trying to change label from another class

Posted 25 June 2011 - 10:27 AM

Is the Game form already open or hidden? If so, you can use this to get the instance of the form..

Game gameForm = Application.Forms["Game"] as Game;
gameForm.SetLabel("some text");


Was This Post Helpful? 1
  • +
  • -

#6 farril   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 110
  • Joined: 04-March 09

Re: Trying to change label from another class

Posted 25 June 2011 - 10:41 AM

yeah its already open. Is there any other way of changing the label? I don't really want to have to use the windows.forms reference in this .cs file

i like the return value idea, however i'm not sure if i could use it.

I call OnConnect by using

        public static void Connect()
        {

            try
            {
                client = new TcpClient();
                client.BeginConnect(IPAddress, Config.Port, OnConnect, client);

            }
            catch (Exception ex)
            {

            }

        }

        public static void OnConnect(IAsyncResult result)
        {
            try
            {
                if (client.Connected)
                {
                    NStream = client.GetStream();
                    MStream = new MemoryStream();

**Change label here**
                }
                else
                {
**Change label here**
                }
            }
            catch (Exception ex)
            {

            }

        }


Was This Post Helpful? 0
  • +
  • -

#7 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6537
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: Trying to change label from another class

Posted 25 June 2011 - 11:29 AM

Tutorials for accessing one class/form from another:
Bulding an application - Part 1
Building an application - Part 2
Quick and easy custom events
Passing values between forms/classes



3 years of college and they didn't teach you this, or that you need an instance of an object in order to use it, or how to read and comprehend an error message? There's $20,000 down the toilet. Let me point you to some resources that are free and books that will cost you $50 each or less that should bring your education WAY up in less than 6 months.


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
Debugging in detail
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? 0
  • +
  • -

#8 farril   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 110
  • Joined: 04-March 09

Re: Trying to change label from another class

Posted 25 June 2011 - 11:38 AM

i hope you copied and pasted that response, because that was a long reply just for me :P

yeah your completely right, i took c# at uni, and picked it up well, but the programs where very basic (most complex was a command line client/server chat program and a command prompt based snake game)

however i'm 4 years out of uni, and have hardly touched programming since.

my intention was to start with a project i wanted to do, and google each problem i came up against. buts its not going completely to plan.

think i'll take your advice, buy a book and try some more simple programs.
Was This Post Helpful? 0
  • +
  • -

#9 eclipsed4utoo   User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1536
  • View blog
  • Posts: 5,972
  • Joined: 21-March 08

Re: Trying to change label from another class

Posted 25 June 2011 - 01:34 PM

tlhIn`toq has some links about Events. Using those would be the correct way of updating the label from another class. Your other class would have a public event that would be fired when something happens. The form would subscribe to that event. When it occurred, the form would update the label.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1