Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Working With Information Across Forms.


  • Please log in to reply
13 replies to this topic

#1 CommittedC0der

CommittedC0der

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1065 posts
  • Programming Language:C#
  • Learning:C#, JavaScript, PL/SQL

Posted 01 January 2011 - 12:27 PM

Hey everyone, welcome to what I believe is the first tutorial of 2011! :c-cool:

In this Tutorial we'll be tackling a very common question amongst new .NET programmers, which is how to work with information across forms. What do I mean by "work across forms"? I mean using methods, variables, and control properties, from Form2 on Form1 or vise versus.

So lets get started!

#1 Setting up our forms for this tutorial.
Ok, to start, open up your C# IDE (I have Micrsoft Visual C# Express 2010), create a new form application, File > New Project > Windows Form Application. Now we need a second form to work with, so right click the solution and goto Add > Windows Form and leave the name as Form2.
(Tip: dont know what the solution is? Goto Project > Add Windows Form, at the top of the compiler)

Ok now that we have our forms setup lets add a button to each one. Form1 button should say "Not Clicked", Form2 button should say "Form1 Button Not Clicked". Alright now time for a little bit of code! So we need to show Form2 when we start the program. So lets create an instance of Form2 and call in subForm, then show it. To do this we add this code in Form1:
public Form1()
        {
            InitializeComponent(); 
            subForm.Show();[COLOR=green]//This shows our form on start up.[/COLOR]
        }
        Form2 subForm = new Form2();[COLOR=green]//This creates a instance of Form2 so we may show it.[/COLOR]


#2 Calling a variable from Form2 on Form1.

Alright now that we have Form2 up and running when we start the program lets declare a variable in Form2, which im sure you know how to do.
public Form2()
        {
            InitializeComponent();
        }
        
        public int Num = 1;
Now lets call this variable in Form1 on button click. Double Click the button on Form1 and add this code:
MessageBox.Show(Convert.ToString(subForm.Num));[COLOR=green]//subForm is the instance of Form2 we created and 'Num' is variable we wanted to access.[/COLOR]
You can also change the 'Num' variable from Form1 like this:
subForm.Num = 5;
Now debug you application and see if it works.


#3 Calling a method from Form1 thats coded in Form2.
First lets add a method to Form2 that we can call from Form1. Add this code two lines below where we created the variable in Form2:
public void ChangeText()
        {
            button1.Text = "Form1 Button Clicked";
        }
Ok now we have a method that changes the text of the button, but we need to call it soooo back to Form1's button click event.

Now in Form1's button click we need to call the method like so:
subForm.ChangeText();[COLOR=green]//Once again 'subForm' is the Form2 instance we made, and 'ChangeText();' is that method we want to call.[/COLOR]
Run your program and Form2's button text should change.

#4 Accessing information in Form1 from Form2.
Alright now we know how to access code in Form2 from Form1 lets do the opposite and learn how to access properties of controls, eg we'll change the button text in Form1 from Form2.

Now this is where it starts to get a little more complicated, but dont worry im sure you'll under stand. First lets goto the code of Form2, and declare an instance of Form1. So add this code directly under where we declared the 'int' variable earlier.
public Form1 mainForm;[COLOR=green]//Notice how this code is a little different? Its because where not creating a new instance of Form1, we just creating an instance or variable that needs to be assigned to Form1.[/COLOR]
Now lets head back to Form1 and add some code. Ok so just above where we show Form2 were going to assign this 'mainForm' to Form1:
public Form1()
        {
            InitializeComponent();
            subForm.mainForm = this;[COLOR=green]//Now we declare the 'mainForm' instance to 'this' which refers to the form your coding in, which in this case is Form1.[/COLOR]
            subForm.Show();          
        }
Now that we can access information on Form1 from Form2, lets change Form1's button text via Form2's method.

In Form2's 'ChangeText' method lets add this code:
mainForm.button1.Text = "This Button Was Clicked";[COLOR=green]//We refer to 'mainForm' which is Form1, then to Form1's button text and change it.[/COLOR]
Now you probably thinking what am i doing wrong?!? I have an error:
'WorkingAcrossForms.Form1.button1' is inaccessible due to its protection level'

This is because Form1's button properties are set to private. To fix this click the button on Form1 and open the properties window, scroll down until you see Modifiers and change it from 'Private' to 'Public'. Now run your application, and Form1's button text should change!

Well thats my tutorial, I hope you enjoyed it, and learned how to work across form, while still being able to understand clearly what was going on! +rep, comments, and questions welcome, I also attached the working project.

Good Day ~ Committed. :)

[ATTACH]3606[/ATTACH]

Attached Files


Edited by Alexander, 02 January 2011 - 03:22 AM.
( modified prefix )

  • 3
There IS a war going on for your mind.
Nothing of eternal significance happens besides prayer.

#2 sam_coder

sam_coder

    CC Addict

  • Senior Member
  • PipPipPipPipPip
  • 380 posts

Posted 01 January 2011 - 03:57 PM

Very nice! while I think this specific scenario is improbable in the real world, it does effectively lay out how this would be done, and will likely be insightful to those who ask this question.
Great Job!

I have two complains. Though I'm coming from a 100% constructive perspective, no trolling, I promise. =)

I wouldn't have marked the tutorial as Intermediate, and you're using the word 'Compiler' incorrectly here.

Ok, to start, open up your C# Compiler (I have Micrsoft Visual C# Express 2010),


Microsoft Visual C# Express is your IDE (Integrated Development Environment), which does indeed have a compiler

anywho, I look forward to reading more

Edited by sam_coder, 01 January 2011 - 03:57 PM.
spelling error

  • 0

#3 CommittedC0der

CommittedC0der

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1065 posts
  • Programming Language:C#
  • Learning:C#, JavaScript, PL/SQL

Posted 02 January 2011 - 12:35 AM

Ahh sam_coder, i was hoping you'd post! You seem pretty knowledgeable in C#. Anyway im glad you thought the tutorial was nice, and yes the scenario is rather improbable but its just meant to give you a clear understanding of how to work across forms. As for your two complaints i agree, its been a while and I should of said IDE not Compiler :P And i wasnt sure if I should mark it beginner or intermediate, but i decided on intermediate for some reason. Ill see if I can change it to beginner.

Thanks for the feed back ~ Committed
  • 0
There IS a war going on for your mind.
Nothing of eternal significance happens besides prayer.

#4 sam_coder

sam_coder

    CC Addict

  • Senior Member
  • PipPipPipPipPip
  • 380 posts

Posted 02 January 2011 - 02:37 AM

I'm glad you took that the right way, I honestly meant no offence. =)
I was glad to see someone post something about this, and I'm not really sure why forms cause this type of confusion. I secretly think it in some way has something to do with VB, and VB's roots. =)

in VB, you can add a form to a project, and you don't really even have to make an instance of that form. You can just add the form to your project, name it something like 'frmWhatever', and then frmWhatever.visible = true (though don't quote me on the syntax, that's been a while)

in that case, you could frmMain.Text = "new value", from frmWhatever, without really having to think about instances of forms..

anyways... I'm done making noise.. I've limited mental capacity to do so at the moment anyways. =)
  • 0

#5 Alexander

Alexander

    YOL9!

  • Moderator
  • 3963 posts
  • Location:Vancouver, Eh!
  • Programming Language:C, Java, C++, PHP, Python, JavaScript, Perl, Delphi/Object Pascal, Visual Basic .NET, Assembly, Fortran, Bash, Others

Posted 02 January 2011 - 03:23 AM

Thank you CommittedC0der for your submission!
  • 0

All new problems require investigation, and so if errors are problems, try to learn as much as you can and report back.


#6 CommittedC0der

CommittedC0der

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1065 posts
  • Programming Language:C#
  • Learning:C#, JavaScript, PL/SQL

Posted 02 January 2011 - 05:49 PM

I'm glad you took that the right way, I honestly meant no offence. =)

No offense taken as Im always open to improving my tutorials. :)

Thank you CommittedC0der for your submission!

You welcome, and thanks for the rep. :)
  • 0
There IS a war going on for your mind.
Nothing of eternal significance happens besides prayer.

#7 John

John

    CC Mentor

  • Moderator
  • 4450 posts
  • Location:New York, NY

Posted 02 January 2011 - 07:34 PM

Nice tutorial. +rep
  • 0

#8 CommittedC0der

CommittedC0der

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1065 posts
  • Programming Language:C#
  • Learning:C#, JavaScript, PL/SQL

Posted 02 January 2011 - 07:37 PM

Thank you, John. :)
  • 1
There IS a war going on for your mind.
Nothing of eternal significance happens besides prayer.

#9 gokuajmes

gokuajmes

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 483 posts

Posted 02 January 2011 - 07:58 PM

really neat tutorial +rep
Sheva Software looks neat :D saw the updated post on Website Reviews
  • 0

#10 CommittedC0der

CommittedC0der

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1065 posts
  • Programming Language:C#
  • Learning:C#, JavaScript, PL/SQL

Posted 02 January 2011 - 08:58 PM

Thanks for the rep, and glad my site looks better. :D
  • 0
There IS a war going on for your mind.
Nothing of eternal significance happens besides prayer.

#11 Tonchi

Tonchi

    Helping the world with programming

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1249 posts
  • Location:Zagreb
  • Programming Language:C#, Others
  • Learning:C, C++, Python, JavaScript, Transact-SQL, Assembly

Posted 01 March 2011 - 01:58 PM

Commited question for you

debugger gives me next

Error 2 'EtsDtb.Tehnicar_za_racunalstvo.Tablica1' is inaccessible due to its protection level

i was just trying to write code exactly like you did
i have created instance for Form2 in Form1 code and trying to access just name of method from Form2
what should i do???
  • 0

#12 CommittedC0der

CommittedC0der

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1065 posts
  • Programming Language:C#
  • Learning:C#, JavaScript, PL/SQL

Posted 01 March 2011 - 02:51 PM

Hi, Tonchi. I assume "Tablica1" is a control on the form? Do you follow this step?

Now you probably thinking what am i doing wrong?!? I have an error:
'WorkingAcrossForms.Form1.button1' is inaccessible due to its protection level'

This is because Form1's button properties are set to private. To fix this click the button on Form1 and open the properties window, scroll down until you see Modifiers and change it from 'Private' to 'Public'. Now run your application, and Form1's button text should change!

~ Committed. :)
  • 1
There IS a war going on for your mind.
Nothing of eternal significance happens besides prayer.




Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download