Help With Methods/Classes

Post here about scripting and programming for HaloPC (audio, network, ai, etc.)
Post Reply
User avatar
WaywornMmmmm




Coroner

Posts: 1341
Joined: Sat Nov 05, 2005 5:17 am
Location: U.S.A

Help With Methods/Classes

Post by WaywornMmmmm »

As most know, I'm fairly new to programming. For the first part of this, I think I know what I'm doing, and the second part is where I need the real help.

First I want to make a new class. I do Project > Add Class and name my class "Class1.cs". Then delete the comments inside

Code: Select all

public Class1()
{
}
Then I make my method

Code: Select all

public void textBoxTextChange()
{
}
Then I start the actual codeing.



This is the part where I'd say I don't know what to do. I have 10 buttons on my form and what I want is for when a buttons is pressed it adds or in some cases replaces the text in textBox1 with the text of the button clicked. I think the code would be a little something like this.

Code: Select all

if (textBox1.Text == "0.")
     textBox1.Text = //code for current button's text here
else
    textBox1.Text = textBox1.Text + //code for current button here
At this point,(I'm doing this in code at the same time) I realized that I can't access the textBox1 in code in the class. This makes me think that I have to use the class that I get when I create a form, I don't know how to do this.

I hope this isn't too confusing for anybody wishing to help.

-Thanks
User avatar
[cc]z@nd!




Literarian 500

Posts: 2297
Joined: Tue May 04, 2004 1:52 pm
Location: michigan

Post by [cc]z@nd! »

i don't know anything about C#, but i know a bit about C++, although regrettably not alot about classes...

what's the code as a whole look like? i'm thinking maybe it would be easier to check through if i saw everything as a whole, or is this some sort of WYSIWYG type program you're using where you only code in snippets?

maybe you could try using a function outside the class before trying to use the class? also, is this an excercise for a book or something?
ASPARTAME: in your diet soda and artificial sweeteners. also, it's obviously completely safe. it's not like it will cause tumors or anything. >.>
always remember: guilty until proven innocent
User avatar
FleetAdmiralBacon




Critic Pyre Articulatist 500

Posts: 2377
Joined: Sat Nov 26, 2005 7:01 pm
Location: Ohio
Contact:

Post by FleetAdmiralBacon »

The button's label can be grabbed with:

Code: Select all

Button1.Text
Why are you doing a whole class + method thing?
If you simply use the form editor, you can make your form, double click the button you want to use, and add the code in the method it generates.
Image
Everything you'll ever need to know about me.
Need help with Linux, C#, C, Python, Java, PHP, Javascript, CSS, or VB? I'm available from 3:00PM-8:00PM EST on weekdays.
User avatar
WaywornMmmmm




Coroner

Posts: 1341
Joined: Sat Nov 05, 2005 5:17 am
Location: U.S.A

Post by WaywornMmmmm »

Well, thank you for replying. I am using a class instead of the method of retyping all the code over again but changing the button part, for two reason. One is that it seems slightly easier, and two, is that I want to try to improve on my knowlage of programming.

I think it might help you understand a little if i just ask the questions a little more straight foward:
1.Where would I put my code inorder for it to be in the class created by a form(I think it might be called the global class?)?

2.Is there a word like "this" that would refer to the control which event I'm writing code for?

3.If there isnt a word like that then is there a way to get a similar effect?

Again, I'm sorry if I'm unclear.
-Thanks
User avatar
FleetAdmiralBacon




Critic Pyre Articulatist 500

Posts: 2377
Joined: Sat Nov 26, 2005 7:01 pm
Location: Ohio
Contact:

Post by FleetAdmiralBacon »

You could write a function that passes in the text of the button.
AddText(Button1.Text);
The other option is to use the sender object (... that does exist in C#, right?), which returns the object that sent the action (in this case, being pressed). I think (not positive here) that it would return the button, in which case, you can c+p with no modifications over to all your buttons...


Good ol' VB6 allowed for arrays of controls within the form editor, which was great because you'd have one method for pressing any of the buttons in set X, and it would actually look at that specific button, etc.

What with .net, I'm pretty sure all of that is gone.
Classes, however, seem pointless here.
How many buttons do you think you'll have in total? Is it really so many that you can't just copy it over to each one and make the necessary changes?
Image
Everything you'll ever need to know about me.
Need help with Linux, C#, C, Python, Java, PHP, Javascript, CSS, or VB? I'm available from 3:00PM-8:00PM EST on weekdays.
User avatar
WaywornMmmmm




Coroner

Posts: 1341
Joined: Sat Nov 05, 2005 5:17 am
Location: U.S.A

Post by WaywornMmmmm »

Well, it is ten buttons that have similar codeing, but if instead of useing if... statments I use switch statments, I would use the method for maybe 20+ buttons.

If you could go into depth on "sender objects" I think I would learn a little something

Also If you could answer my the #1 question from my previous post I would appreciate it. I don't really want you to go indepth with classes, just where it is and where to type my code for it. Even if I don't use it now, I think it would be good to keep in knowlage.
Supermodder911




Connoisseur Coroner

Posts: 1262
Joined: Sun Sep 03, 2006 10:43 pm
Location: Michigan

Post by Supermodder911 »

ok if you want to do this by clicking a button the easy way i can help in a class i probably cant.To make that happen try these examples double click the button to add a class to the form

Code: Select all

//under the button class this would go
textBox1.Text = whatever the buttons name is;

/*and just do this for each button that would work but in your case i think you made a class for it i wouldnt really know how to even start that lol im new too perhaps we can learn together though*/

Image
C Wizzle
User avatar
FleetAdmiralBacon




Critic Pyre Articulatist 500

Posts: 2377
Joined: Sat Nov 26, 2005 7:01 pm
Location: Ohio
Contact:

Post by FleetAdmiralBacon »

You'll want to double click somewhere in your form, ignore the "On Load" stub it generates, and jump down under it remaining within the form's class.
Basically, somewhere before the last } and after the public class Form1 : Windows.Forms.Form {
(I think that's what it is, haven't done much with forms in C# recently)
Double click a button in a form and post the stub it generates (the code the cursor is wrapped around once it jumps to the code view), I haven't the time to start up C# (which takes abnormally long on my computer, even with its 1g of ram and dual core processor)

@supermodder911: We've established that already.
Image
Everything you'll ever need to know about me.
Need help with Linux, C#, C, Python, Java, PHP, Javascript, CSS, or VB? I'm available from 3:00PM-8:00PM EST on weekdays.
Supermodder911




Connoisseur Coroner

Posts: 1262
Joined: Sun Sep 03, 2006 10:43 pm
Location: Michigan

Post by Supermodder911 »

o ok srry tryin to help
Image
C Wizzle
User avatar
WaywornMmmmm




Coroner

Posts: 1341
Joined: Sat Nov 05, 2005 5:17 am
Location: U.S.A

Post by WaywornMmmmm »

FleetAdmiralBacon wrote:..."On Load" stub ... stub it generates (the code the cursor is wrapped around once it jumps to the code view)
I'm not really sure what you mean by these stubs. It might be something implimented in VS 2005 (I'm doing all my work in 2003).

I think I understand the form class now, thanks.

Also @ supermodder I'd enjoy learning C# with a few others. I'm already kind of working with people and I'm sure they wouldn't mind it if you joined. I will aim you sometime.
OwnZ joO




Articulatist 500

Posts: 980
Joined: Thu Nov 10, 2005 4:24 pm

Post by OwnZ joO »

I can tell you that you dont want to do this in another class, you will want to do this in your form class, because there's really no point in using another class.

Code: Select all

        private void button_Click(object sender, EventArgs e)
        {
            //On a button click handler(this is a button click event handler)
            //The sender will be a button
            //Since we know the sender is a button, but it's an object
            //We must cast it to a button
            textBox1.Text = ((Button)sender).Text;
        }
K right-click on your form in the solution explorer, and click view code.
Then past this private void in. Then double click on all of the button's in your form(in the designer, not when debugging). It'll make button click handlers for each one, but what you wanna do is delete all of them but this one. Then click the green arrow to debug your project, it'll give you a bunch of errors, but that's ok. Double click on the first one, and it'll take you to it. It'll say:

Code: Select all

     this.button1.Click += new System.EventHandler(this.button1_Click);
K a little explaining, Click is an event that happens(is fired) when you click on button1. You add an EventHandler to it, which is the private void button1_Click(object sender, EventArgs e) that you deleted to get this error. Well the function I provided you with has object sender and EventArgs e, so just replace the (this.button1_Click) with (this.button_Click) - the name of the function I provided.
Do this with all of the error's for the button event handlers, and then run your application, that should work. I didn't tell you anything about classes, but I explained a little bit about events and event handlers(not very well, and not very in depth)
User avatar
Prey




Connoisseur Snitch! Pyre Articulatist 500

Posts: 1026
Joined: Wed Dec 27, 2006 6:49 am
Location: UK
Contact:

Post by Prey »

There is a much easier way than that jo0, and I thought the point here was to use an external class.

First, highlight the 10 buttons you have on your form, open the events pane, and double-click the 'Click' action. This will link every highlighted control's click event to one central click handler (button_click in the code below).

Now highlight the textbox in the designer, and in the properties pane under Design you'll find the Modifiers property. This controls the level of access to the selected control. Currently it is only accessible by the form on which it is placed (private), but seeing as we want to use it from an external class we will need to set this to public.

Now add a new class to your form (Class1 in the code below).

Form1.cs

Code: Select all

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        private Class1 class1;

        public Form1()
        {
            InitializeComponent();
            this.class1 = new Class1(this);
        }

        private void button_Click(object sender, EventArgs e)
        {
            Button btn = (sender as Button);
            class1.SetText(btn.Text);
        }
    }
}
Class1.cs

Code: Select all

using System;
using System.Collections.Generic;
using System.Text;

namespace WindowsApplication1
{
    public class Class1
    {
        private Form1 form1;

        public Class1(Form1 form1)
        {
            this.form1 = form1;
        }

        public void SetText(string text)
        {
            if (form1.textBox1.Text == "0.")
            {
                form1.textBox1.Text = text;
            }
            else
            {
                form1.textBox1.Text += text;
            }
        }
    }
}
Note that a Form1 instance is passed in to class1, who then stores it away for later to access the textbox. (Note that if you hadn't changed the textbox's modifier, the textbox would have not appeared in the intellisense list, and you would have also recieved a compile-time error if you had still tryed to use it).

You have to understand that because Form1 is a reference type (an object) by passing it in as a parameter a new copy of it is not made, but a reference. Meaning Class1's form1 is a pointer to the actual form. So even once you've set Class1's form1, If you make any changes to Form1 it'll all happen in Class1's form1 too (because Class1 doesn't really have a form1, just a pointer to one). In memory, the reference will be stored on the stack, whilst the actual data (the form1) will be on the heap/free store.

The exception to this is value types (like int, short, long, etc), which when passed in will be copied, meaning if you did pass in an integer from Form1 to Class1, changing it in Form1 would not have any effect on the one passed in to Class1. Value types are stored completely on the stack.

If you do for some reason need to keep the same instance of a value type, you can add the ref keyword: 'public void Hello(ref int num)'. This will mean any changes made in the Hello function to num, will be reflected in Form1's num (assuming thats where you called the function). Note that attaching ref to a reference type has no effect.
Halo 2 Prophet - Skin with ease with the simple 3D point and click interface.
Halo 3 Research Thread - Contribute to the research into Halo 3.
OwnZ joO




Articulatist 500

Posts: 980
Joined: Thu Nov 10, 2005 4:24 pm

Post by OwnZ joO »

Nice to know about the highlighting them all and double clicking the click action, but he asked if using a class would be good in this situation, and there's really no point in my opinion, it doesn't really teach him anything about using classes anyway, I could write him an explaination of classes and how to use them, but there are plenty of those on the internet anyway. Also I've just been taught and agree in general that it's bad practice to have public fields, and I agree with it in general or else I wouldn't listen to it. Also I was just trying to explain it to him at a beginners level.
User avatar
Prey




Connoisseur Snitch! Pyre Articulatist 500

Posts: 1026
Joined: Wed Dec 27, 2006 6:49 am
Location: UK
Contact:

Post by Prey »

OwnZ joO wrote:he asked if using a class would be good in this situation
Hmm no he didn't, but yes I agree in this situation it is pointless to use an external class, but only because the entire app is pointless. It is still good to know how to access controls from a form via a class though, which was the point here.
OwnZ joO wrote:Also I've just been taught and agree in general that it's bad practice to have public fields, and I agree with it in general or else I wouldn't listen to it.
Yes public fields are never a good idea, unless their const's. What should actually be being used is accessors. They are slightly more advanced though and that is why I though not to include them. Here is how they are implemented though, for the record:

Form1.cs

Code: Select all

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        #region Instance Data

        private Class1 class1;

        #endregion

        #region Accessors

        ///<summary>
        /// Class1
        ///</summary>
        public Class1 Class1 { get { return class1; } set { class1 = value; } }
        ///<summary>
        /// TextBox1
        ///</summary>
        public TextBox TextBox1 { get { return textBox1; } set { textBox1 = value; } }

        #endregion

        public Form1()
        {
            InitializeComponent();
            this.Class1 = new Class1(this);
        }

        private void button_Click(object sender, EventArgs e)
        {
            Button btn = (sender as Button);
            Class1.SetText(btn.Text);
        }
    }
}
Class1.cs

Code: Select all

using System;
using System.Collections.Generic;
using System.Text;

namespace WindowsApplication1
{
    public class Class1
    {
        #region Instance Data

        private Form1 form1;

        #endregion

        #region Accessors

        ///<summary>
        /// Form1
        ///</summary>
        public Form1 Form1 { get { return form1; } set { form1 = value; } }

        #endregion

        public Class1(Form1 form1)
        {
            this.Form1 = form1;
        }

        public void SetText(string text)
        {
            if (Form1.TextBox1.Text == "0.")
            {
                Form1.TextBox1.Text = text;
            }
            else
            {
                Form1.TextBox1.Text += text;
            }
        }
    }
}
Note Wayworn, accessors are used because it allows you to seperate the details of how the data is stored from how it is used. By using accessor functions, you can later change how the data is stored without having to rewrite any of the other functions in your program that use the data.
Halo 2 Prophet - Skin with ease with the simple 3D point and click interface.
Halo 3 Research Thread - Contribute to the research into Halo 3.
Post Reply