473,753 Members | 7,825 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to pass information, classes between forms in Windows Applicationmode


Keywords: scope resolution, passing classes between parent and child
forms, parameter constructor method, normal constructor, default
constructor, forward reference, sharing classes between forms.

Here is a newbie mistake that I found myself doing (as a newbie), and
that even a master programmer, the guru of this forum, Jon Skeet,
missed! (He knows this I'm sure, but just didn't think this was my
problem; LOL, I am needling him)

If you want to pass information between two forms comprised of
classes, whether or not they are parent/child, modal or modeless,
dialog or non-dialog you have to use the non-normal/ non-default or
parametricized or parameter constructor, not a default (no parameter)
normal constructor. Explanation below.

Let's say you have a button on your form that you click to bring up
another form, and the button has an Events handler called
"clikMeButton2B ringUpANew_Chil d_Form_to_The_M ainForm_Click".

Let's say in Designer mode you've already built a nice new (child or
second or dependent or non-main) form called "Form2" (I think you can
also programmically 'build' a new form, but I like using the Designer
mode, drag-and-drop and let the Wizard figure out how to initialize
the form, but I digress).

Let's say you have a class, called Class1, that you declared in your
first form, during instantiation of that form, having an instance
"myClass1", and now you want that same class instantiation to be
passed to the Form2. How to do that? If you use the wrong
constructor it won't be 'seen' by the new form. Hence you must do
this:

private void
clikMeButton2Br ingUpANew_Child _Form_to_The_Ma inForm_Click(ob ject
sender, EventArgs e)
{
// Form2 frm2 = new Form2(); //Do not do this--it won't
work! You cannot see myClass1 in frm2

Form2 frm2 = new Form2(myClass1) ; // this will work;
myClass1 will be seen in Form2
// of course, we assume you do have a parameter constructor in Form2
that accepts class1 as a parameter, ie., you have a constructor with
this signature in Form2 (Class1 C1) {};//see further below at (#1)

frm2.Show(); //shows the form, etc
}

That's it. Done. You can also pass more than one class of course,
with the proper signature.

(#1) And just to make the point clearer, Form2 must have as a
constructor something besides the normal (default) non parameter
constructor, along these lines:

public Form2(Class1 passClass1_from _Form1)
{
myClass2_that_e xists_in_Form2 = passClass1_from _Form1; //
names are arbitrary of course

InitializeCompo nent();

// other stuff here if you want
}

Done.

One more thing as an aside, and it has nothing to do with the above:
you need, in Form 1, to be careful where you put class1; it has to be
sort of like C++, and placed as a 'forward reference' before Form1 is
constructed, along these lines:

public partial class Form1 : Form
{
Class1 myClass1; //Note where this is located! outside the
default constructor for Form1
// this is called a 'forward reference' in C++, and you need to do
this for C# as well
public Form1()
{
InitializeCompo nent(); //mandatory for all forms, stuff
that the Wizard fills and I don't fool with

myClass1 = new Class1();
//or, if your Class1 takes parameters int i, string s, myclass1=new
Class (10, "hi");

//other stuff here, like, for example, this.AutoValida te =
AutoValidate.En ableAllowFocusC hange; //etc

}

/// other stuff here

}

The point being: you need a forward reference if the Class1 is not
'nested' in the Form1 {}, that is, if Class1 is part of a separate
translation unit or module, even if Class1 is in the same namespace as
Form1.

RL
Jul 21 '08
12 11105
On Jul 23, 11:40 pm, raylopez99 <raylope...@yah oo.comwrote:
raylopez99 <raylope...@yah oo.comwrote:
In that case I guess it's the end of the discussion.

I did learn a few things in this exchange, which I'll summarize
below. Thanks for replying.
I'm glad.
I didn't realize you were such a stickler for complete code, I assumed
you were just being obstinate. I'll make a mental note of it for any
future reference.
It really makes a huge difference. Apart from anything else, if you
can come up with a short, complete example you can cut and paste *all*
of it into a post, avoiding any spurious changes.
You claimed forms and console apps were "totally different". They're
not. Even the entry point is the same - a Main method.

OK, if you say so. I don't even know where "Main" is in Windows
anymore, but I assume it's there somewhere.
In a WinForms app generated by Visual Studio, it's in Program.cs.
Including Main in a class isn't the same as creating a nested class -
and it's *always* in a class (or struct) so it's not a "convention " -
it's part of how you *have* to define methods.

Yes, but it doesn't address the issue of scope, etc. But let's move
on.
If all you meant was that you wanted to see the Main method in a
different class, that would have been fine. It was your complaint that
it was "nested" in a class which was odd.
But I wrote the program in Windows Form application mode, not console
mode. I could reproduce a Windows Form error in Console mode, I would
be quite the experienced programmer, no?
Not really. It's quite a simple transformation, if you're not actually
using any WinForms code. In fact, you could just have deleted the
designer files, deleted the calls to InitializeCompo nent, made the
classes not derive from Form, and then change Program.cs to call a
method within your class instead of running Application.Run .

If you'd explained that you were having trouble doing the conversion,
I'd have helped with that - but instead you insisted that everything
was different in WinForms apps.

<snip>
If I'm that competent a programmer, I would not need you or anybody
else to spot errors in my code; I would not make errors in the first
place.
No, that's really not how it works. Being able to demonstrate
something in a console app really doesn't take much knowledge. If
console apps effectively scare you, it's well worth writing some.
They're a lot easier to work with than WinForms apps when you don't
actually need a GUI. For instance, displaying information is just a
matter of calling Console.WriteLi ne instead of fiddling around with
message boxes etc.

I strongly recommend that you play around with them a bit. One hint:
put a call to Console.ReadLin e() at the end of your Main method so you
can see what's happened before the program terminates. (I don't do
this for my simple console apps usually because I build and run them
from the command line, where it's not an issue. It's really just in
Visual Studio.)

<snip>
While you fail to use correct terminology, even after being corrected
on it, communication is difficult. Likewise it is harder to comment on
a program when I'm only given half the code.

But your lingo is not conducive to the free flow of information. It's
like first having to repeat a magic number before I get an answer.
You told me the magic number five posts ago, but I forgot it.
Then review the posts! There's not much point in me telling you
something if you completely ignore it and forget it. Learning the
right terminology is a vital part of learning how to communicate about
a programming language. Imagine if you were trying to learn English
grammar, but you kept calling nouns verbs... it would make everything
terribly confusing.
Study and commit to memory, I've added a few Easter Egg comments
tailored just for you Jon:
Here it is:
////////// START OF PARTIAL CLASS FORM1: Form
public partial class Form1 : Form
{
Class1 myClass1; //cannot comment out this line--compile error
<--do you know why, Jon?
Obviously - you're referring to it in the constructor.

Really? A constructor in my "book" is the stuff that appears in public
Form1 () {//here}, but I guess I'm using the wrong lingo again.
Anyway, moving right along...
Yes, and you were referring to it there - near the bottom. You also
referred to it in the event handling method - sorry that I didn't
mention that as well.
However, you could move the declaration to after the contructor and
methods - or even to a different file which also declares Form1 (again
as a public partial classs).

Oh, really? OK, I just tried this and it doesn't compile (sorry in
advance about the incomplete code, but you know how that goes)...

///////start
namespace MDIForms
{
Class1 myClass1; //// error CS0116: A namespace does not
directly contain members such as fields or methods

public partial class Form1 : Form
{
//Class1 myClass1; //manditory for compiling

//////end
It still needs to be within a class declaration for Form1 - but you
could have moved it to just before the end of the class, e.g. after
the event handling method.
I try to avoid doing it in other cases, however.'

OK, I did get that, I think, as I understand the code fragment you
gave is perfectly legal (this.something =something; is not the same as
something=somet hing;) and gives the intended result, unlike my
commented out code.
Yup. Using "this.myCla ss1" means "I want to refer to the instance
variable myClass1 belonging to "this" object, instead of a local
variable which happens to also have the name myClass1.
The default value of a reference type non-local variable is null. As
for whether it's "bad" that depends on the context. Sometimes it's
exactly what you want - but not in this case.

Understood. I even saw in a Windows App event handler some code like:

MyDialogForm01 dlgForm = new MyDialogForm01( );
//stuff deleted here
dlgForm = null; // at end of code; not strictly needed, apparently
some form of manual garbage collection
Avoid code like that. Setting a local variable to null at the end of
the method has no effect, and certainly doesn't trigger garbage
collection. In fact the object could have been collected before that
line of code, if nothing else references it.

(There are some situations involving captured variables where setting
a local variable to null *would* have an effect - probably an
unintended one - but that's a more complication situation. I mention
it only for completeness.)
Yes, you're using it to pass information to Form2. As we've already
discussed, there are other ways of doing that.

True enough, though in my mind other than the example of inheriting a
form, and using a method from a class that's nested in the base class,
I really don't see how. Far more flexible to pass objects--oops, I
meant variables--to the second or derived form. I mentioned in
passing that you can maybe use delegates/events between forms, but the
more I think about it, the more I see that getting the events
recognized might be a problem. Maybe you can insert "delegate <type>
VariableName (type)" throughout both forms, and maybe that will work,
but without seeing an example I'm not about to waste an hour or two
trying to find out. Besides there's a hoary tradition in C++ of using
the constructor to pass all kinds of information
<snip>

Certainly using a constructor this way is fine. Aside from anything
else, it's vital if you want to make the type immutable, which is
often a good thing.
Nope, the classes aren't hidden at all. To prove it, just write:
new Class1(0, "");
new Class2();
in the constructor. Obviously it won't do a lot of good (unless those
constructors do interesting things) but the fact that it compiles
proves that the classes aren't hidden.

OK, thanks for that terminology. *Hiding is not the best word, perhaps
'local variable overriding of outer scope (?) variables of the same
name'. *Or something like that. OK I got it. *Or maybe not. *Moving
right along...
No, "hiding" is the right word - it's class that was the wrong word.
The local variable certainly wasn't *overriding* the instance variable
- that would suggest some kind of odd local polymorphism. If you don't
like the word "hiding" then "shadowing" is also fine.
At that point variables myClass1 and mYClass2 would refer to the nested
classes; the constructor call to Class1 within the Form1 constructor
wouldn't compile as the appropriate constructor signature hasn't been
declared, and clikMeNewFToolS tripMenuItem_Cl ick wouldn't compile
because the types of the Form2 constructor call would be incompatible.

Interesting, thanks. *You left out an important detail--when there is
ambiguity, how can you tell the compiler to 'override' the ambiguity
and compile? *In C# there is no easy way, for example, if the Class1
and Class2 variables are in namespace XYZABC, you can maybe write
XYZABC.Class1 myClass1; etc., but everytime I tried this it doesn't
compile *(Update: *I see the 'this' pointer below solves some
ambiguity)
"this" will solve it to refer to variables, but if there's ambiguity
in the class names themselves, using the namespace is usually enough
to fix it. If it's still not (and there can be times where it's not
enough) you can use global::Namespa ce.Goes.Here.Cl assname

If that's *still* not enough (because you're referring to two types
which have the same fully qualified name but are in different
assemblies) you can use extern aliases - but try not to :)
Hiding is a perfectly fine word to use - but saying you're declaring a
class when you're actually declaring a variable is hugely misleading.

OK, noted. *If this is in your book I'll study it, but likely if not
I'll forget it five minutes after I post this thread.
This kind of thing isn't in my book, I'm afraid - my book is aimed at
people who already know C# 1 reasonably well. Hopefully I *use*
terminology accurately though, so it's possible that it'll sink in by
osmosis :)

(If you've already got C# 3.0 in a Nutshell then I'd stick with that
until you're reasonably comfortable with the C# 1 features. It's a
good book. If you want a bit more of a "deep dive" into the C# 2 and 3
features, that's when my book would be helpful.)

<snip>
then the program will work without a NullReferenceEx ception.

Wow! *You're good. *I played around and see what you're talking about,
even though I'm not 100% clear on why the 'this' pointer (the object
calling 'Form1()') makes such a difference, but maybe the object/
variable understand to use the 'outermost' Class1. *Leaving out the
'this' pointer did give a nice compiler warning CS0136, which, had I
seen it before, would have obviated having to write this entire thread
(though I guess I would not have learned as much).
Hopefully my explanation of the use of "this" above explained the
matter, but let me know if you want more detail (and a sample app :)
// here is what I played with, comments from compiler and hoving
ToolTips

this.myClass1 = new Class1(100, "heLlO1YouTube! "); //Class1
Form1.myClass1
Yup.
//failure to use 'this' above gives a compiler error: error CS0136: A
local variable named 'myClass1' cannot be declared in this scope
because it would give a different meaning to 'myClass1', which is
already used in a 'parent or current' scope to denote something else
I think you've got different code again then - because you'd normally
only see that if you had multiple scopes within the method, and
declared the variable twice within those scopes. For instance:

class ScopeDemo
{
int variable; // Instance variable

public void Method()
{
// Local variable - hides or shadows the instance variable
int variable;

{ // Create a new scope
// Declare another local variable - this causes CS0136
int variable;
}
}
}

// Class with Main in just so we can compile as a console app.
// Actually running this app does nothing. We could have
// removed this class and compiled as a class library instead.
class Test
{
static void Main() {}
}

That will generate CS0136. If you remove either of the local variable
declarations, it will compile. There will be warnings because we're
not actually *using* the variable, but it's only when there are
multiple local variable declarations that you see CS0136 - and that
would occur even without the instance variable existing at all.

Hope that helps,
Jon
Jul 24 '08 #11
On Jul 24, 1:58*pm, raylopez99 <raylope...@yah oo.comwrote:

<big snip - glad it was useful>
All in all, this thread reinforced my prejudice that you should stick
to canonical ways of building programs--learned through trial and
error--rather than understand, as you apparently have, the inner
workings of the C# language. *Unless you plan to write a book on C#.
Hmm. Each to their own I guess, but I personally would really hate
trying to code in a language which I didn't really understand.

Fortunately Eric Lippert has written about this in a much more
eloquent way than I can:
http://blogs.msdn.com/EricLippert/ar.../01/82168.aspx

Jon
Jul 24 '08 #12
On Jul 25, 11:50*am, raylopez99 <raylope...@yah oo.comwrote:
I do understand the C# code, not like you understand it, but enough to
write a decent program in console mode
I don't want to sound patronising, and I know I will anyway, but: you
really can't know how well you understand something unless either you
created it in the first place, or you've explored so much of it that
you're aware of how much more there is.

Per my geneology console mode program in C#, I wrote a program that
works, because it proved a theorem that was proved (by hand) over 100
years ago. *So obviously the program is 'working'. *That said, if I
ran it through a profiler I'm sure I would find bottlenecks that could
be eliminated to make the program run even faster. *So there's various
degrees of success in the statement "my program works".
I don't claim that your program doesn't work. It may work very well
indeed. That's not the same as saying you understand it.
I would personally view some of the issues of understanding that you've
demonstrated (and corrected, mind you!) in this thread and a couple of
others as quite fundamental - certainly things I would expect even a
reasonably junior professional coder to understand. I know you're
learning C# as a hobby rather than for a career, and that's great - but
you shouldn't kid yourself that you understand C# yet.

I beg to differ. *I do understand C#, for one thing it doesn't have a
copy constructor like C++, because it passes references to references
or somesuch, probably 'virtually' behind the scenes, but I also
understand how to write a program in C#--not as well as you--but it
works (see above).
That shows you understand *some* C# - enough to get that particular
program written. It doesn't mean you understand C# "in general" or
that your grasp is deep enough to cope when faced with unexpected
behaviour.

<snip>
But at the same time I *do* think it's important at least for
*professional* coders to have a greater understanding of the language
than many do. It shouldn't be black magic. You shouldn't have to guess
what a line of code means, and you certainly shouldn't need to "try it
and see if it compiles" (with the exception of a few bits of type
inference, where that's far quicker than trying to go through the same
process that the compiler would).

But your standard is too high. *And at some level you need commented
code--I'm sure you've seen the example where a programmer is using
obscure syntax and code to say "Hello World!" but it's indecipherable
(done as a joke).
Absolutely, and that's a really bad idea. You certainly should write
the clearest code possible. Whenever I find myself writing "clever"
code, it's almost always the wrong thing to do.
This really applies more to professional coders than hobbyists, but
I've seen (and rejected) a depressing number of interview candidates
who claim to have years of experience, but clearly don't know the
language to any sort of reasonable level.

Your standards are too high. *Do you think India and China have so
many software engineers (and engineers in general) because they have
smarter people than the West? *Or maybe they study the hard sciences
more? *Or, it is because they lower their standards? (it's the latter,
from what I've read from people who know). *Yet they get the job done,
without really "knowing why".
Then they're building up technical debt. It's very easy to rush
products out of the door without knowing how they work. You then pay
for it when you can't make any changes, and when you can't find bugs.

The difference in productivity between someone who understands the
tools they're working with and someone who is just cutting and pasting
from web pages which claim to have snippets of code doing roughly
what's required is *massive*.
>*Ditto for doctors in China--they were
and are mostly technicians, that's why they cannot practice in the USA
easily, since the standards are higher there. *BTW even Scientific
American had an article a few years or decade ago about this issue--
software engineering is too complicated, standards for coding are too
high, take too long to learn, too many bugs (memory leaks anyone?)--
hence (not in the article, but by implication) the "Visual Studio
Wizard" as a step forward, though it is derived originally from the
less capable language of Visual Basic.
Too many bugs and memory leaks you say - now why do you think that is?
That's not because the standards are too *high* - it's because they're
too *low*. When people don't know what they're doing, of course
they'll create bugs.

Now, I'm all for making things simpler, so there's less that people
*do* need to know - and C# is a much simpler language than C++, for
instance. That doesn't mean that a professional coder should feel
comfortable if they don't know what they're doing. For hobbyists it's
somewhat different, but if someone's going to pay you to write code,
you should know what that code means.

Jon
Jul 25 '08 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
3322
by: Zlatko Matiæ | last post by:
Hi everybody! Recently I was struggling with client/server issues in MS Access/PostgreSQL combination. Although Access is intuitive and easy to use desktop database solution, many problems appear when someone is trying to use it as front-end for real server database systems such as PostgreSQL or MySQL. One of these problems is regarding pass-through queries and parameters. I wanted to have all the code on client, while executing it on...
3
25286
by: Todd Schinell | last post by:
Back in July, Jeffery Tan posted this: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=OWOTdf0VDHA.2296%40cpmsftngxa06.phx.gbl In response as to how to get click events from a user control to invoke a method in the parent form. This code doesn't seem to work for me, I've tried it a number of times with very simple test cases (A user control with a single button and a parent form with a single text box) and it always...
8
3366
by: Brian F | last post by:
Exactly what the subject says. I have an ASP page that I want my C# windows application to open in Internet Explorer, and if possible have it send along a list of values from a list box. Thank you.
5
11826
by: Jason Huang | last post by:
Hi, In Global.cs, I have public string myString="". Another 2 forms are Form1.cs, Form2.cs. How do I use the Global.cs' myString to store a string in Form1 and then pass to Form2? Thanks for help. Jason
6
5352
by: juky | last post by:
Hi all, I have 2 applications one in VB.net and the other in VC6. I need to pass data between them. How can I do it? what's the best way to implement such communication ? Any comment will be appreciate. Thank you. Juky
3
8670
by: swb76 | last post by:
I have a Object Oriented question. I got two forms - Form1 and Form2. I also got two classes Class1 and Class2 Form1 has objects Object1 - instance of Class1 and Object2 - instance of Class2. When i load Form1, i load this form and instantiate Object1 and Object2. Please note Object1 and Object2 can be fairly large because of several variables.
3
4029
by: forest demon | last post by:
for example, let's say I do something like, System.Diagnostics.Process.Start("notepad.exe","sample.txt"); if the user does a SaveAs (in notepad), how can i capture the path that the user selects? thanks...
4
2274
by: =?Utf-8?B?bmlja25hbWU=?= | last post by:
I have the following xml Schema: “<?xml version="1.0" encoding="Windows-1252"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified"> <xs:element name="Document"> <xs:complexType> <xs:sequence> </xs:sequence> <xs:attribute name="name" type="xs:string" />
12
2044
by: Nathan Sokalski | last post by:
I have several CustomControls that I have written for my project. However, when I try to compile I recieve the following warning & errors: Warning 32 Could not resolve this reference. Could not locate the assembly "nathansokalski_com_test, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors....
0
9072
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9653
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9421
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9333
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8328
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6869
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6151
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4942
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2284
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.