473,789 Members | 2,807 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Class/Form scope question

Kim
Like
http://groups.google.dk/group/micros...280aaeed78de0/
and
http://groups.google.dk/group/micros...ea4d944b12bf0/
am I trying to access something in a form in one class from another
class. And without luck :(

In my case I tried to change the Text of a Label. Here is my problem:

I'm using Microsoft Visual Studio 2005 Professional Edition.
I have 2 files (Form1.cs and Stuff.cs) with 1 class each and they are
in the same namespace. Form1.cs has a form with some elements, among
these, a label (Label1) and a button (Button1). I made an event so that
when I click on Button1 a fuction in Stuff.cs is called/run.
When the function in Stuff.cs is done, I want to signal this on the
form window by changing the Label1.Text.

I have tried making Label1 public (by default its private). See below,
note that this is inside Form1.cs.
public System.Windows. Forms.Label Label1

When I tried to change the text, from Stuff.cs, like this
Form1.Label1.Te xt= "NewText";
I got a compile error, "An object reference is required for the
nonstatic field, method, or property".

My question is then: How can I change something on an element in a form
in another class but while in the same namespace ?

Jun 22 '06 #1
5 1773
The compile error says it all:

Form1 is a type declaration, not an instance; as far as the compiler is
concerned you could have 400 instances of Form1 all side-by-side : so which
one should it update? To do this using direct access, you *must* have a
reference between the forms. It really comes down to how you are creating
the forms, and how they behave; if you create them together and they both
sit side by side, then you might have something like:

Form1 form1 = new Form1();
Form2 form2 = new Form2();
form2.SomePrope rty = form1;
form1.Show();
form2.Show();

where SomeProperty is defined something like:
public class Form2 : Form {
// ...
private Form1 _someField;
public Form1 SomeProperty {get {return _someField;} set {_someField =
value;}}
}

This now allows any instance of Form2 to have a handle to the corresponding
Form1 instance.

In a simple scenario, you could proably get away with using some static
property, but I don't recommend it.

Also : it is bad practive to make the Label (or whatever) public; at a push,
Internal maybe, but it would be better to encapsulate it

public class Form1 : Form {
// ...
public string MessageCaption {
get {return Label1.Text;} set {Label1.Text = value;}
}
}

Now a Form2 instance can set SomeProperty.Me ssageCaption = "Frodo";

Finally, you may want to consider using an eventing mechanism to communicate
between the forms; a little bit more involved than direct property access,
but (for more complex scenarios) far more extensible.

Marc
Jun 22 '06 #2
"Kim" <ki*****@gmail. com> a écrit dans le message de news:
11************* *********@p79g2 00...legr oups.com...

| I'm using Microsoft Visual Studio 2005 Professional Edition.
| I have 2 files (Form1.cs and Stuff.cs) with 1 class each and they are
| in the same namespace. Form1.cs has a form with some elements, among
| these, a label (Label1) and a button (Button1). I made an event so that
| when I click on Button1 a fuction in Stuff.cs is called/run.
| When the function in Stuff.cs is done, I want to signal this on the
| form window by changing the Label1.Text.

Create a new public event on the form that can be caught in the outside
class.

Handle the button event in a handler on the form and call your public event
from that handler.

After the the public event returns, set the label in the end of the button
handler on the form.

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Jun 22 '06 #3
Kim
Thanks for the quick replies.

Maybe I wasn't clear about, but when I run the program file, my
constructor opens the form window and it's in this window Label1 and
Button1 are.
Creating a new instance of Form1 in Stuff.cs
Form1 somename = new Form1();
is not what I want, as this creates a new window and leaves the first
window unchanged.
The only way the function (lets call it FuncA) can be called is when
the Button1_Click event is trigger in the form window.
The whole idea is that the form window can call functions from Stuff.cs
and some of those functions should give back responses so it can be
noted that the function has been completed.
I can only see one other option to solve my problem, and thats to make
the functions return error_values, which then I must handle in the
event in Form1.cs.

As you might have noticed Im fairly new into C#, so please give
examples.

Marc: As you said, "It really comes down to how you are creating the
forms, and how they behave", I hope this is more clear now what I do
and want.

Joanna: Think I get the idea, but I under what you mean with "Create a
new public event on the form that can be caught in the outside class".
Could elaborate it ?

Jun 22 '06 #4
Kim
Thanks for the quick replies.

Maybe I wasn't clear about, but when I run the program file, my
constructor opens the form window and it's in this window Label1 and
Button1 are.
Creating a new instance of Form1 in Stuff.cs
Form1 somename = new Form1();
is not what I want, as this creates a new window and leaves the first
window unchanged.
The only way the function (lets call it FuncA) can be called is when
the Button1_Click event is trigger in the form window.
The whole idea is that the form window can call functions from Stuff.cs
and some of those functions should give back responses so it can be
noted that the function has been completed.
I can only see one other option to solve my problem, and thats to make
the functions return error_values, which then I must handle in the
event in Form1.cs.

As you might have noticed Im fairly new into C#, so please give
examples.

Marc: As you said, "It really comes down to how you are creating the
forms, and how they behave", I hope this is more clear now what I do
and want.

Joanna: Think I get the idea, but I under what you mean with "Create a
new public event on the form that can be caught in the outside class".
Could elaborate it ?

Jun 22 '06 #5
"Kim" <ki*****@gmail. com> a écrit dans le message de news:
11************* *********@b68g2 00...legr oups.com...

| Joanna: Think I get the idea, but I under what you mean with "Create a
| new public event on the form that can be caught in the outside class".
| Could elaborate it ?

public partial class Form1 : Form
{
...

#region public event

private EventHandler button1Clicked;

public event EventHandler Button1Clicked
{
add { button1Clicked += value; }
remove { button1Clicked -= value; }
}

#endregion

private void button1_Click(o bject sender, EventArgs args)
{
if (button1Clicked != null)
{
button1Clicked( sender, args);
label1.Text = "some value";
}
}
}

public class Stuff
{
private void HandleForm1Butt on1Click(object sender, EventArgs args)
{
// do something
}

public void ShowForm()
{
Form1 test = new Form1();
test.Button1Cli cked += HandleForm1Butt on1Click;
test.Show;
}
}

But better still would be to pass an instance of Stuff to the constructor of
the form, then your event handlers can work directly on the object.

public partial class Form1 : Form
{
...

private Stuff stuff;

public Form1(Stuff stuff)
{
this.stuff = stuff;
}

private void button1_Click(o bject sender, EventArgs args)
{
stuff.DoSomethi ng();
label1.Text = "some value";
}
}
}

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Jun 22 '06 #6

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

Similar topics

30
2278
by: Neil Zanella | last post by:
Hello, Suppose I have some method: Foo::foo() { static int x; int y; /* ... */ }
2
1607
by: JJ | last post by:
Hi, I am trying to understand the lifetime or scope of a class in this project. Here is the code that I am talking about: private void PopulateCategoryCombo() { ListItem objListItem;
6
7766
by: Carlos | last post by:
Hi all, I am trying to access a public field of another form class within the same namespace. The field is public, what is the best way to access it from a different class? I defined as private MyNameSpace.Form1 cForm1; and I am trying to use it later as TextBox.Text = cForm1.TextBox.Text;
4
1680
by: Dean | last post by:
I finally got class session variables to work by putting the following in global.asax in the session_start: dim myDBComp as DBComp = new DBComp........ session("myDBComp") = myDBComp In each aspx codebehind module I can define my object right after the class definition as so: dim myDBComp as DBComp The problem I had was where to put the instantiation:
19
4921
by: Jamey Shuemaker | last post by:
I'm in the process of expanding my knowledge and use of Class Modules. I've perused MSDN and this and other sites, and I'm pretty comfortable with my understanding of Class Modules with the exception of custom Collection Classes. Background: I'm developing an A2K .mdb to be deployed as an .mde at my current job-site. It has several custom controls which utilize custom classes to wrap built-in controls, and add additional functionality....
2
1698
by: Gman | last post by:
Hi, I have created a usercontrol, a grid control essentially. Within it I have a class: clsGridRecord. I have coded the events such that when a user clicks on the grid, say, the events occur on the parent form. This is fine. The problem occurs when I want to raise an event for a user clicking on one of the clsRecords which are on the grid. So I've placed: Public Event GridRecordClicked(ByVal rec As clsGridRecord,
2
3525
by: Michael | last post by:
Hello, I have a newbie question about class scope. I am writting a little program that will move files to one of two empty folders. I am having a hard time understanding scope. So this will be a two part question. Part 1: I have a form with a text box on it that I want to spit out results to. Sample code:
9
2360
by: Rudy | last post by:
Hello All! I'm a little confused on Public Class or Modules. Say I have a this on form "A" Public Sub Subtract() Dim Invoice As Decimal Dim Wage As Decimal Static PO As Decimal Invoice = CDec(txbInv.Text) Wage = CDec(txbTotWage.Text)
16
1794
by: Robert Dufour | last post by:
Here's the class code snippet Imports System.Configuration.ConfigurationManager Public Class Class1 Public _strTestSetting As String Public Sub SetTestsetting()
0
9666
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
9511
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,...
1
10142
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
9986
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...
1
7529
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
5422
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...
1
4093
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
2
3703
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2909
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.