473,765 Members | 1,963 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Still confused about passing data between forms (or classes)

AMP
Hello,

I have this in form1:
namespace Pass
{
public partial class Form1 : Form
{
public Form2 form2;
public Form1()
{
InitializeCompo nent();
}

private void button1_Click(o bject sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
}

public void label1_Click(ob ject sender, EventArgs e)
{

}

}
}
and I have this in form 2:
namespace Pass
{
public partial class Form2 : Form
{
public Form1 form1;
public Form2()
{
InitializeCompo nent();
}

private void button1_Click(o bject sender, EventArgs e)
{
form1.label1.Te xt = "I changed for you";
}
}
}

When I push the button in form1 I create and show form 2,
but when I push the button in form 2 , I get an error that it doesnt
know about form 1 anymore.
The label in form 1 is public.

Besides an explanation about what is wrong, I would like a good
explanation about passing classes and class properties around so any
class doesnt have a problem "seeing"the m.

Much, Much Thanks
Mike

Aug 26 '06 #1
7 10394
Mike,

Why not just attach a property to your Form2 class like so:

public Form1 Form1
{
get
{
return form1;
}
set
{
form1 = value;
}
}

Then, when you create Form2, you do this:

Form2 form2 = new Form2();
form2.Form1 = this;
form2.Show();

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"AMP" <am******@gmail .comwrote in message
news:11******** **************@ 75g2000cwc.goog legroups.com...
Hello,

I have this in form1:
namespace Pass
{
public partial class Form1 : Form
{
public Form2 form2;
public Form1()
{
InitializeCompo nent();
}

private void button1_Click(o bject sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
}

public void label1_Click(ob ject sender, EventArgs e)
{

}

}
}
and I have this in form 2:
namespace Pass
{
public partial class Form2 : Form
{
public Form1 form1;
public Form2()
{
InitializeCompo nent();
}

private void button1_Click(o bject sender, EventArgs e)
{
form1.label1.Te xt = "I changed for you";
}
}
}

When I push the button in form1 I create and show form 2,
but when I push the button in form 2 , I get an error that it doesnt
know about form 1 anymore.
The label in form 1 is public.

Besides an explanation about what is wrong, I would like a good
explanation about passing classes and class properties around so any
class doesnt have a problem "seeing"the m.

Much, Much Thanks
Mike

Aug 26 '06 #2
AMP
This doesnt work.I'm probobly missing something.
I posted a question a few years ago concerning the same thing.And if I
remember correctly, I need to have a Field in both forms that reference
each other.
If you know of any working examples(sample s) in c# online I would like
to know the urls.
I guess I need commented code.
Thanks
Mike

Nicholas Paldino [.NET/C# MVP] wrote:
Mike,

Why not just attach a property to your Form2 class like so:

public Form1 Form1
{
get
{
return form1;
}
set
{
form1 = value;
}
}

Then, when you create Form2, you do this:

Form2 form2 = new Form2();
form2.Form1 = this;
form2.Show();

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"AMP" <am******@gmail .comwrote in message
news:11******** **************@ 75g2000cwc.goog legroups.com...
Hello,

I have this in form1:
namespace Pass
{
public partial class Form1 : Form
{
public Form2 form2;
public Form1()
{
InitializeCompo nent();
}

private void button1_Click(o bject sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
}

public void label1_Click(ob ject sender, EventArgs e)
{

}

}
}
and I have this in form 2:
namespace Pass
{
public partial class Form2 : Form
{
public Form1 form1;
public Form2()
{
InitializeCompo nent();
}

private void button1_Click(o bject sender, EventArgs e)
{
form1.label1.Te xt = "I changed for you";
}
}
}

When I push the button in form1 I create and show form 2,
but when I push the button in form 2 , I get an error that it doesnt
know about form 1 anymore.
The label in form 1 is public.

Besides an explanation about what is wrong, I would like a good
explanation about passing classes and class properties around so any
class doesnt have a problem "seeing"the m.

Much, Much Thanks
Mike
Aug 26 '06 #3
"AMP" wrote :

"This doesnt work.I'm probobly missing something. I posted a question a few
years ago concerning the same thing.And if I remember correctly, I need to
have a Field in both forms that reference each other. If you know of any
working examples(sample s) in c# online I would like to know the urls. I
guess I need commented code."

.... snipped for, I hope, clarity and brevity ...

Mike, you should take any response from Nicholas Paladino
10-to-the-twentieth-power more seriously than any response from me, but this
is an area where I initially struggled, and then later simply learned to
relax : it wasn't as hard as I had made it in my head. Your mileage may
vary.

Consider you have a WinForm app that creates an instance of the basic Form1
at run-time. Take a look at your program.cs file where you'll see :

Application.Run (new Form1());

You add another WinForm, Form2, to your project in Visual Studio or whatever
IDE.

In the body of the Form2 Class definition you insert the 'Form1 property as
shown by Nicholas.

Now you define a 'Load EventHandler for Form1, inside that handler you
insert a pointer to Form1 itself into the property of Form2 named Form1.
There are other places where you could put that initialization code, but the
Load event is a common sense starting point.

That's what Nicholas is showing you in this code fragment : (I'm just
wrapping his code in a Load event handler)

// by declaring form2 here we make it available anwhere in the scope of this
Class (Form1)
private Form2 form2;

// the Load event is called automatically when Form1 is instantiated in the
Program.cs class in the Main routine of the application
private void Form1_Load(obje ct sender, EventArgs e)
{
// set 'form2 to a new instance of the WinForm Class named Form2
form2 = new Form2();

// by assigning to the Form1 property of the new instance of Form2,
you are automatically using its 'set method.
// 'this will automatically refer to the running instance of Form1
itself
form2.Form1 = this;

// now show form2 : you have to make it appear ... but that could be
done later as required
form2.Show();
}
Now you may be thinking how can you get a pointer in Form1 to Form2 : well,
that one just requires you create a variable in Form1 that you can use
anywhere in Form1. Obviously if you create the 'form2 variable inside the
Load event handler, it will be scoped only to the Load event. That's why we
declare form2 outside the Load event.

Apologies to you and Nicholas if I have introduced any confusion into the
discussion.

best, Bill Woodruff
dotScience
Chiang Mai, Thailand
Aug 26 '06 #4
AMP
Thanks,
Im almost there...And I really appreciate all your help.THANKS
I can get the textbox in form1 to change from the button in form2
But... I have just a few more questions: I have commented the code with
my questions
First, the code...
Form 1

public partial class Form1 : Form
{
Q1->public Form2 form2; //Why are we holding a reference to form2
here?

public Form1()
{
InitializeCompo nent();

}

private void button1_Click(o bject sender, EventArgs e)
{
Form2 form2 = new Form2();
Q2- form2.propForm1 = this; //What is this doing?
form2.Show();

}

public void label1_Click(ob ject sender, EventArgs e)
{

}

public void button2_Click(o bject sender, EventArgs e)
{
form2.label1.Te xt = "I changed for you also";
}

}
}
Form2:
public partial class Form2 : Form
{
Q3-public Form1 form1; //Why the reference AND the following
property?
public Form1 propForm1
{
get
{
return form1;
}
set
{
form1 = value;
}

}

public Form2()
{
InitializeCompo nent();
}

private void button1_Click(o bject sender, EventArgs e)
{
form1.label1.Te xt = "I changed for you";
}
}
}
Q4-How do I change the text in Form1. (The label is public)

Bill Woodruff wrote:
"AMP" wrote :

"This doesnt work.I'm probobly missing something. I posted a question a few
years ago concerning the same thing.And if I remember correctly, I need to
have a Field in both forms that reference each other. If you know of any
working examples(sample s) in c# online I would like to know the urls. I
guess I need commented code."

... snipped for, I hope, clarity and brevity ...

Mike, you should take any response from Nicholas Paladino
10-to-the-twentieth-power more seriously than any response from me, but this
is an area where I initially struggled, and then later simply learned to
relax : it wasn't as hard as I had made it in my head. Your mileage may
vary.

Consider you have a WinForm app that creates an instance of the basic Form1
at run-time. Take a look at your program.cs file where you'll see :

Application.Run (new Form1());

You add another WinForm, Form2, to your project in Visual Studio or whatever
IDE.

In the body of the Form2 Class definition you insert the 'Form1 property as
shown by Nicholas.

Now you define a 'Load EventHandler for Form1, inside that handler you
insert a pointer to Form1 itself into the property of Form2 named Form1.
There are other places where you could put that initialization code, but the
Load event is a common sense starting point.

That's what Nicholas is showing you in this code fragment : (I'm just
wrapping his code in a Load event handler)

// by declaring form2 here we make it available anwhere in the scope of this
Class (Form1)
private Form2 form2;

// the Load event is called automatically when Form1 is instantiated in the
Program.cs class in the Main routine of the application
private void Form1_Load(obje ct sender, EventArgs e)
{
// set 'form2 to a new instance of the WinForm Class named Form2
form2 = new Form2();

// by assigning to the Form1 property of the new instance of Form2,
you are automatically using its 'set method.
// 'this will automatically refer to the running instance of Form1
itself
form2.Form1 = this;

// now show form2 : you have to make it appear ... but that could be
done later as required
form2.Show();
}
Now you may be thinking how can you get a pointer in Form1 to Form2 : well,
that one just requires you create a variable in Form1 that you can use
anywhere in Form1. Obviously if you create the 'form2 variable inside the
Load event handler, it will be scoped only to the Load event. That's why we
declare form2 outside the Load event.

Apologies to you and Nicholas if I have introduced any confusion into the
discussion.

best, Bill Woodruff
dotScience
Chiang Mai, Thailand
Aug 27 '06 #5
I have a question about this that perhaps someone could enlighten me
about. For some time now I have been passing the reference from one
form to the other via the constructor of the second form as follows:

namespace Pass
{
public partial class Form1 : Form
{
public Form2 form2;
public Form1()
{
InitializeCompo nent();

}

private void button1_Click(o bject sender, EventArgs e)
{
Form2 form2 = new Form2(this);
form2.Show();
}
}

and then my second form would look like this:

namespace Pass
{
public partial class Form2 : Form
{
public Form1 form1;
public Form2(Form1 f1)
{
this.form1 = f1;
InitializeCompo nent();
}

private void button1_Click(o bject sender, EventArgs e)
{
form1.label1.Te xt = "I changed for you";
}
}

}

Is there anything inherently wrong with the way I am doing things? It
has been working fine, I just want to make sure I am getting myself in
the habit of proper coding techniques.

Thanks,
Travis Calvert

Aug 28 '06 #6

travisj wrote:
I have a question about this that perhaps someone could enlighten me
about. For some time now I have been passing the reference from one
form to the other via the constructor of the second form as follows:

namespace Pass
{
public partial class Form1 : Form
{
public Form2 form2;
public Form1()
{
InitializeCompo nent();

}

private void button1_Click(o bject sender, EventArgs e)
{
Form2 form2 = new Form2(this);
form2.Show();
}
}

and then my second form would look like this:

namespace Pass
{
public partial class Form2 : Form
{
public Form1 form1;
public Form2(Form1 f1)
{
this.form1 = f1;
InitializeCompo nent();
}

private void button1_Click(o bject sender, EventArgs e)
{
form1.label1.Te xt = "I changed for you";
}
}

}

Is there anything inherently wrong with the way I am doing things? It
has been working fine, I just want to make sure I am getting myself in
the habit of proper coding techniques.

Thanks,
Travis Calvert
Generally this is a bad idea. It comes with two problems.

First, you can only ever use a Form2 in conjunction with a Form1. If,
someday, you discover that it would be useful to have a Form2 working
together with a Form3, you're hooped.

Second, Form2 knows intimate details about how Form1 is put together.
If someday you decide that label1 shouldn't be a label after all, but a
RichTextBox (because you want to display something with fancy fonts or
formatting) then you're hooped.

There are two ways to improve your design. I always use the second, not
the first, but it depends upon your needs. Your current design is what
is called "very tightly coupled": a FOrm2 works _only_ with a Form1 and
knows about the internals of Form1.

The first alternative is less tightly coupled, so it's better, but not
optimal. First, you should replace a direct reference to
form1.textBox1. Text with a property. Second, you should create an
interface that declares that property. So:

public interface IHasGreeting
{
string GreetingText { get; set; }
}

Now you say that Form1 implements this interface:

public class Form1 : Form, IHasGreeting
{
...
public string GreetingText
{
get { return this.textBox1.T ext; }
set
{
if (value == null) { throw new
ArgumentNullExc eption("value") ; }
this.textBox1.T ext = value;
}
}
}

Finally, you say that Form2 will work with any form that implements
IHasGreeting:

public class Form2 : Form
{
IHasGreeting form1;

public Form2(IHasGreet ing greetingForm)
{
this.form1 = greetingForm;
}

private void button1_Click(o bject sender, EventArgs e)
{
this.form1.Gree tingText = "Hello world";
}
}

Of course, "GreetingTe xt" should be some name descriptive of what the
thing is.

Notice that this does two things: first, Form2 no longer knows how
Form1 displays its text; second, Form2 will work with _any object_ that
implements IHasGreeting, whether it be a Form1, a Form3, or some other
object.

The second way involves even more loose coupling. This is the method I
tend to use. Have Form2 raise an event when something interesting
happens (the user presses the Hello button) and offer a property from
which a caller can fetch any required information. Form1 then
subscribes to this event and does whatever it wants to with the
information.

public class Form2 : Form
{
private string _greeting = "";

public event System.EventHan dler UserSaidHello;

public string UserGreeting { get { return this._greeting; } }

private void button1_Click(o bject sender, EventArgs e)
{
this._greeting = "Hello world.";
if (UserSaidHello != null) { UserSaidHello(t his,
System.EventArg s.Empty); }
}
}

public class Form1 : Form
{
private void button1_Click(o bject sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.UserSaidH ello += new
System.EventHan dler(form2_User SaidHello);
form2.Show();
}

private void form2_UserSaidH ello(object sender, System.EventArg s e)
{
Form2 f2 = (Form2)sender;
this.textBox1.T ext = f2.UserGreeting ;
}
}

Now Form2 is completely ignorant of the environment in which it is
being used. It notifies any interested parties when the user clicks the
button, and offers a property that interested parties can read when the
event happens. Any object can use Form2: just subscribe to the event.

One refinement to this second approach is to create a custom event
arguments type that passes the greeting string as part of the event,
but this is necessary only in certain multithreading scenarios, in
which the UserGreeting property could change between the time that the
event is raised and the time that the event handler fetches the
property value.

Either of these two approaches--an interface or an event--is better
than passing a form reference to another form, from an O-O point of
view.

Aug 28 '06 #7
Mr. Wood,

Thank you for taking the time to elaborate. Your sharing of knowledge
is greatly appreciated.

Travis Calvert

Aug 28 '06 #8

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

Similar topics

1
2642
by: Rob Oliver | last post by:
Hi, I've seen a walkthrough for passing data from a setup project to a custom action (an application) with an InstallClass. I am curious though--can the data also be intercepted by a custom action defined as a vbscript? If so, does anyone have any idea how it would be accomplished? Thanks! Rob Oliver
3
4759
by: Simon Harvey | last post by:
Hi, In my application I get lots of different sorts of information from databases. As such, a lot of information is stored in DataSets and DataTable objects. Up until now, I have been passing around chunks of data in DataTables/DataSets, simply because that was the format that they were in when the data was taken from the database. Now, I know this maybe a pretty silly question with a standard "it depends" answer, but I'm going to...
1
1058
by: msyez | last post by:
HI, I have 3 pages where I collect userdata that I want to show in a confirmationpage. Which is the best way of passing data from page1 to page4, page2 to page4 and so on? I like public property and context.handler way but i just works between sequential pages doesn't it? Do I have to use Sessions? Is there a more OOP way of implementing it (a general class instead of in every code-behind page)? Should you put an object in SessionState? Use...
3
2685
by: Marc Castrechini | last post by:
First off this is a great reference for passing data between the Data Access and Business Layers: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnanchor/html/Anch_EntDevAppArchPatPrac.asp I use my own classes in the Business layer. I want to keep the Data Access layer from requiring these classes so I tried passing a Datarow between the layers and it seems to work good for me. Constructing the datarow in the Class...
11
4144
by: Macca | last post by:
Hi, I'm writing an application that will pass a large amount of data between classes/functions. In C++ it was more efficient to send a pointer to the object, e.g structure rather than passing the actual structure itself. Is this true of C# also?
4
2135
by: Andreas Pfiz | last post by:
Hello, I have a problem with passing Data between a "classic ASP-Page (VBScript)" and a ASP.NET 2.0 Page using showModalDialog / window.returnValue ------------------------------------------------------------- Here is the Code-Snippet from the "caller" page: var rValue="oldValue"; rValue = showModalDialog(test.aspx?,'Name','dialogHeight:400px; dialogWidth:800px;');
0
1143
by: Bernie Beattie | last post by:
I'm new to ASP.NET 2.0 and I'm trying to get my head round the best way to approach data access for a website. According to the various articles I have read so far, it is best to separate out data access code into classes which reside in the App_code directory. Preferably I would want generic data access classes which can be used on multiple websites as we may have different front-end pages for different clients but accessing the same data...
4
4163
by: moondaddy | last post by:
I have a htm page where I need to pass some data to an aspx page as a means of sending data to the database. I don't need to see the aspx page so I was going to put it in a hidden iframe. This works real good. Since I don't need the aspx page to do any postback, is there a way to pass a parameter to it with out it finishing the round trip back to the htm page? Thanks. -- moondaddy@newsgroup.nospam
3
349
by: OG | last post by:
I'm trying to learn C# 2008 on Microsoft's MSDN. Their walkthrough example on passing data between forms at http://msdn.microsoft.com/en-us/library/ms171925.aspx had this error in the C# version when I tried it: 'PassingDataBetweenForms.Form2' does not contain a definition for 'Form2_Load' and no extension method 'Form2_Load' accepting a first argument of type 'PassingDataBetweenForms.Form2' could be found (are you missing a using...
1
1606
by: kondi69 | last post by:
Hello, I'm right newbe in c# but I have big problem with passing data between forms. Below code: : public Form1 main = new Form1(); public int opuwminuty;
0
9568
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
9399
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10163
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...
0
10007
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8832
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
7379
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
5276
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3924
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.