C# How to get variable to a different form - c#

I have two windows forms. One of them has a variable.
In that form, I have created a get method:
public string getUSERID
{
get
{
return userID;
}
}
In the second form, I am attempting to use this method like so:
private void Form2_Load(object sender, EventArgs e)
{
UserID = Form1.getUSERID();
}
For reasons I do not understand, the second form does not recognize getUSERID as a viable method for Form1, and I have no idea why.
I've searched the forums, and the answer I keep finding is exactly what I did: build a "get/set" method, and activate it with FormX.get/set.
Is there anything I'm doing wrong here?
EDIT: To calrify - Form 1 is the first form that opens. While it's open, I am opening Form 2 from within form 1 like so:
Form Form2 = new Form2();
Form2.Show();
conn.Close();
Hide();
(The connection is because form 1 used a connection until now).
Now, since I'm opening Form2 before I hide Form1, I thought that the data in Form1 would still be available during FormLoad of Form2, so I can extract the variable from it, then close Form1.

After your clarification, what would i do is this. In Form2 create a parameter constructor,like this:
string form1UserId="";
public Form2(string UserID)
{
InitializeComponent();
this.form1UserId=UserID;
}
And then, from Form1 you just have to do this:
Form2 frm2 = new Form2(userID);
frm2.Show();
conn.Close();
Hide();
Hope this helps.

Two things are wrong here. First is that you define getUSERID as a property but are trying to access it like a method. Second is that you define getUSERID as a non-static method but are trying to use it as a static method. To fix the first problem, rename getUSERID to USERID in your property declaration and access it without the parentheses (i.e. someForm.USERID). To fix the second problem, you'll need to access the USERID property from an instance of Form1, not as a static member on the class Form1, like so:
Form2.cs
private Form1 _f1;
public Form2(Form1 f1): Form2()
{
_f1 = f1;
}
// ...
private void Form2_Load(object sender, EventArgs e)
{
UserID = _f1.USERID;
}

You've defined it as a property, not a method, so no () is needed.
Also, to access it without creating an instance (new Form1()), it would have to be static.

the second form does not recognize getUSERID as a viable method
That's because it isn't a method, it's a property. Omit the parens, and you'll find it works.

Here in your case getUSERID is a read only property of string type, which will return the userID of that class. And one more thing to be noticed is that the property is not defined as static so an object reference is required to access the property value; so the signature of the page load will be
private void Form2_Load(object sender, EventArgs e)
{
Form1 newForm1= new Form1();
UserID = newForm1.getUSERID; // UserID will be same as that of Form1's userID
}
You can define the property as static inn-order to avoid creating instance. if so you can access the same property from any other forms without creating instance of the form1. So the definition of the Class Form1 will be like the following
public class Form1
{
private static string _UserId = "Some value";
public static string UserId
{
get { return _UserId; }
}
// rest of statements
}
So that you can access the UserId from any other forms by using Form1.UserId no need to create an instance of the Form1

public **static** string getUSERID
{
get
{
return userID;
}
}
private void Form2_Load(object sender, EventArgs e)
{
UserID = Form1.getUSERID(); // If the property has static it's possible to write like this.
}
(or)
public string getUSERID
{
get
{
return userID;
}
}
private void Form2_Load(object sender, EventArgs e)
{
Form1 f= new Form1();
UserID = f.getUSERID();
}

Just give the second form the variable when you open it, like so:
SecondForm f2 = new SecondForm(YourVariable);
f2.Show();
//Global Variable
var SaveVariableFromForm1;
protected override void OnCreate(var YourVariable)
{
//Imagine this is the Form2 OnCreate();
SaveVariableFromForm1 = YourVariable;
}
And catch the variable on the 2ยบ Form's OnCreate Method save it in a Global Variable and use it were ever you feel like it, hope this helps.

Related

How to access chart property of Form2 from Form1 by clicking button action of Form1 in C# [duplicate]

I am trying to understand whats the difference between a static and public properties. But when I tried to access my public property 'Test' in other form it says 'null'.
Heres Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string _test;
public string Test
{
get { return _test; }
set { _test = value; }
}
private void Form1_Load(object sender, EventArgs e)
{
_test = "This is a test";
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.Show();
}
}
Here's Form2:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
Form1 frm1 = new Form1();
label1.Text = frm1.Test;
}
}
To check the value of 'Test' in Form1, I put a breakpoint to this line:
label1.Text = frm1.Test;
But the value is 'null'.
Please help me how can I access public properties to other forms.
And BTW I tried to make this public property be a 'public static'. I can access this using this:
Form1.Test
But I noticed that I can change 'Test' value from Form2 which I don't want to happen. That's why I am trying to use public property but with no luck. Can somebody clarify me these things. Thanks for all your help guys!
EDIT: (For follow up question)
Sir John Koerner's answer is the best answer for my question. But I have a follow up question, I tried to make these 'test' properties to be a 'static', and I noticed that even if I make this property a static or public property, it still can be edit in Form2. To make myself clear here's a sample:
public partial class Form2 : Form
{
private Form1 f1;
public Form2(Form1 ParentForm)
{
InitializeComponent();
f1 = ParentForm;
}
private void Form2_Load(object sender, EventArgs e)
{
label1.Text = f1.Test;
}
private void button1_Click(object sender, EventArgs e)
{
f1.Test = "This test has been changed!";
this.Close();
}
}
After Form2 closed, I tried to break again in Form1_Load to check value of 'Test', and it was changed! How can I make a public property in Form1 to readOnly in Form2 and cannot be editted? Please clarify to me. Thanks a lot guys!
Your property is an instance variable, so the value can be different across different instances of Form1.
If you are trying to access instance variables from a parent form, the easiest way to do that is to pass Form1 in to the constructor of Form2.
public partial class Form2 : Form
{
private Form1 f1;
public Form2(Form1 ParentForm)
{
InitializeComponent();
f1 = ParentForm;
}
private void Form2_Load(object sender, EventArgs e)
{
label1.Text = f1.Test;
}
}
Then when you create a new Form2 from Form1, you can do this:
Form2 frm2 = new Form2(this);
If you want your property to be read only, you can simply not specify a setter:
public string Test
{
get { return _test; }
}
Use of this method 'static'
At first Control label property Modifiers=Public
in Program code below
public static Form1 frm1 = new Form1();
public static Form2 frm2 = new Form2();
in Form1 code below
Program.frm2.show();
in Form2 code below
label1.Text=Program.frm1.text;
The frm1 not your main form object. It is newly created object where property Test initializes when it loads (in Form1_Load event handler).
The first instance of Form1 shows an instance of Form2, and then Form2 creates another instance of Form1. This could work, but you set _test in the Form.Load event, which:
Occurs before a form is displayed for the first time.
You do not show the instance of Form1 you're trying to read Test from, so its Load event will not occur and Test remains null.
You could add a constructor overload or property to pass the Form1 reference as #JohnKoerner mentions, but I would prefer to only pass the required variable, perhaps even encapsulated in an event, to reduce coupling. Form2 usually doesn't need to know all about Form1.
public
The type or member can be accessed by any other code in the same assembly or another assembly that references it.
static
The static modifier on a class means that the class cannot be instantiated, and that all of its members are static. A static member has one version regardless of how many instances of its enclosing type are created.
A static class is basically the same as a non-static class, but there is one difference: a static class cannot be externally instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself.
However, there is a such thing as a static constructor. Any class can have one of these, including static classes. They cannot be called directly & cannot have parameters (other than any type parameters on the class itself). A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced. Looks like this:
static class Foo()
{
static Foo()
{
Bar = "fubar";
}
public static string Bar { get; set; }
}
Static classes are often used as services, you can use them like so:
MyStaticClass.ServiceMethod(...);

Timer not getting control textbox data

So im trying to execute a method from a Timer the problem is that everytime i call the method and pass a string as argument, automatically the string is set to NULL and that's weird, is there a fix or something, here is some code if you wish to look at it
private void timer1_Tick(object sender, EventArgs e)
{
int currentHour = FixTime(DateTime.Now.ToString("hh tt"));
int currentMinute = FixTime(DateTime.Now.ToString("mm tt"));
int currentSeconds = FixTime(DateTime.Now.ToString("ss tt"));
string currentTT = DateTime.Now.ToString("tt");
int userHour = Settings.Default.hour;
int userMinute = Settings.Default.minutes;
int userSeconds = Settings.Default.seconds;
string userTT = Settings.Default.TT;
if (currentHour == userHour && currentMinute == userMinute &&
currentSeconds == userSeconds && currentTT == userTT)
{
MakeThePost(postTextBox.Text); // the postTextBox.Text field automatically is set to null
}
}
private void MakeThePost(string data)
{
string text = data;
if (!String.IsNullOrEmpty(text))
{
fb.Post("me/feed", new { message = text });
}
else
MessageBox.Show("Nothing to post on facebook", "Field is empty",MessageBoxButtons.OK, MessageBoxIcon.Error);
}
UPDATE: So aparently the problem isnt in the timer or even in the MakeThePost the real problem is in another form iam trying to display, when its displayed the constructor makes a new Form1 object, why i make this?, because i want to have access to the controls in the main form, but when i execute the Form1 constructor to make a new object, the Form1 postTextBox control stop updating its Text property, so is there another way to access main Form controls without initializing an object?
The posted code doesn't seem to contain anything that would cause the postTextBox.Text property to become null.
There has to be something else in your application that nulls that property. Make sure Data Binding is not silently setting this to null.
Insert breakpoints both on the line calling MakeThePost, and on the first line of MakeThePost, then run the application.
See if the property is null only before the call, or both before and inside the method.
EDIT:
According to your latest edits, it seems you're creating a new Form1 instance, whereas you should probably pass a reference to the existing one when instantiating Form2
Add a Form2 constructor that takes a Form1 object as parameter:
public partial class Form2 : Form
{
private Form1 otherForm;
public Form2()
{
InitializeComponent();
}
public Form2(Form1 frm) : this()
{
otherForm = frm;
}
//Other methods and properties of Form2
}
Then create a new instance of Form2:
Form2 secondForm = new Form2(form1Instance);
Now, inside the Form2 instance, you have the otherForm reference, which will allow you to call public members of the Form1 instance. You might have to change the access modifier on some Form1 members to make them public.

Fully access a control from another Form

I have a main Windows Form (From1) which has a TextBox in it. I've also created another Windows Form (FindReplaceForm) which I'm going to use for implementing a form of find and replace dialog. I need to fully access all the properties and methods of my textbox in From1 from FindReplaceForm window.
Although I set the Modifiers property of my TextBox to Public, in FindReplaceForm window I can't access the text in it.
You can access the the owner form in the child using:
((Form1)Owner).textBox1.Text = "blah";
Assuming you have called your the child form using:
Form2 form = new Form2();
form.Show(this);
You need to pass a reference to the control or the form to your constructor so that you can reference the instance of the class. Add an argument of the same type as the calling form to the constructor:
private Form1 calling_form;
public FindReplaceForm (Form1 calling_form)
{
this.InitializeComponent()
this.calling_form = calling_form;
}
Then in your button call you can say:
calling_form.TextBox_value_text.SelectedText = "";
In your code, Form1 is a CLASS, not a variable. When you show your FindReplaceForm you should specify the Owner (just use this).
Now you can the Owner property on FindReplaceForm to get access to Form1.
Showing FindReplaceForm:
FindReplaceForm.Show(this);
In your button click event:
void Buttton1_Click(object sender, EventArgs e)
{
((Form1)this.Owner).TextBox_value_text.SelectedText = "";
}
Even if you set the textbox access modifier back to private, you can simply pass a reference to the textbox in the second form's constructor, thus enabling the second form to manipulate any property of the textbox:
first form:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2(this.textBox1);
frm.Show();
}
}
second form:
public partial class Form2 : Form
{
private TextBox _OwnerTextBox;
public Form2(TextBox ownerTextBox)
{
InitializeComponent();
_OwnerTextBox = ownerTextBox;
this.textBox1.Text = _OwnerTextBox.Text;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
_OwnerTextBox.Text = this.textBox1.Text;
}
}
In your FindReplaceForm.button1_Click function you want to control an object of class Form1. The error in your code explains that you don't call a function of an object of class Form1, but a function of class Form1 itself. The latter can only be done on static functions
You describe that you have an existing Form1 object and that your FindReplaceForm needs to change Form1 by calling functions in Form1. Probably there might be more than 1 Form1 object. Therefor your FindReplaceForm instance somehow needs to know which Form1 object it needs to control. Someone needs to tell this to your FindReplaceForm. This is usually done using the constructor of the FindReplaceForm or using a property.
public class FindReplaceForm
{
private Form1 formToControl = null;
public FindReplaceForm(Form1 formToControl)
{
this.formToControl = formToControl;
}
private void OnButton1_Click(...)
{
this.formToControl.TextBox_Value_Text.SelectedText = ...
}
Another method would be not to put the formToControl in the constructor, but as a property that you can set separately. Both methods have their advantages:
via constructor: your FindReplaceForm knows for sure there is alway a formToControl. The only place you have to check if formToControl really exists is in the constructor.
Using a default constructor with a separate FormToControl property may cause run time errors if people forget to set the FormToControl.
If you have a lot of properties, or some properties may have default values, or may be changed later, then the property method is more flexible.

c# - Use the same element in different forms

I am doing a registration system. In this system I use a modal, another form that is displayed when the user clicks a button.
To show the form, I use:
private void btnShowModal_Click(object sender, EventArgs e)
{
AddUserForm form = new AddUserForm();
form.Show();
}
This works great to show the form. Now this is my problem: if I create one label in this form and try to use it for reference in the primary form I get the error that it does not exist in context. Example, I've created label1 in the AddUserForm. Now I will try to use the same label in Form1 to change the text:
label1.Text = "I was created in AddUserForm and now I'm at Form1!";
...but this don't work, I get the error:
The name 'label1' does not exist in the current context.
How I can use elements in both forms? I need to add a reference? How? Thanks all in advance!
Create a Base form that creates the label. Each form can then inherit from the base form and share it that way.
public class BaseForm : Form
{
//define label
}
public AddUserForm : BaseForm
{
}
In your AddUserForm, create this property:
public string LabelText
{
get { return label1.Text; }
set { label1.Text = value; }
}
Then in your Form1, simply add this line after you create the AddUserForm instance:
form.LabelText = "I was created in AddUserForm and now I'm at Form1!";
More generally, while you could have exposed the field (it's private by default), doing so is a bad idea. Wrapping form elements in properties gives you control over exactly what the outside world can and cannot change. For example, you may not want other classes being able to change the size, location, font, etc. of the label. Or maybe you do, but if so then you add properties specifically for those things you want to be able to be changed.
I think you can try like this,
Form1.cs
private void btnShowModal_Click(object sender, EventArgs e)
{
Form2 frm = new Form2(ref this.label1);
frm.ShowDialog();
}
Form2.cs
Label labelOne = null;
public Form2()
{
InitializeComponent();
}
public Form2(ref Label lbl)
{
InitializeComponent();
labelOne = lbl;
}
private void Form2_Load(object sender, EventArgs e)
{
labelOne.Text = "A";
}
Hope it solves!

C# winform: Accessing public properties from other forms & difference between static and public properties

I am trying to understand whats the difference between a static and public properties. But when I tried to access my public property 'Test' in other form it says 'null'.
Heres Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string _test;
public string Test
{
get { return _test; }
set { _test = value; }
}
private void Form1_Load(object sender, EventArgs e)
{
_test = "This is a test";
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.Show();
}
}
Here's Form2:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
Form1 frm1 = new Form1();
label1.Text = frm1.Test;
}
}
To check the value of 'Test' in Form1, I put a breakpoint to this line:
label1.Text = frm1.Test;
But the value is 'null'.
Please help me how can I access public properties to other forms.
And BTW I tried to make this public property be a 'public static'. I can access this using this:
Form1.Test
But I noticed that I can change 'Test' value from Form2 which I don't want to happen. That's why I am trying to use public property but with no luck. Can somebody clarify me these things. Thanks for all your help guys!
EDIT: (For follow up question)
Sir John Koerner's answer is the best answer for my question. But I have a follow up question, I tried to make these 'test' properties to be a 'static', and I noticed that even if I make this property a static or public property, it still can be edit in Form2. To make myself clear here's a sample:
public partial class Form2 : Form
{
private Form1 f1;
public Form2(Form1 ParentForm)
{
InitializeComponent();
f1 = ParentForm;
}
private void Form2_Load(object sender, EventArgs e)
{
label1.Text = f1.Test;
}
private void button1_Click(object sender, EventArgs e)
{
f1.Test = "This test has been changed!";
this.Close();
}
}
After Form2 closed, I tried to break again in Form1_Load to check value of 'Test', and it was changed! How can I make a public property in Form1 to readOnly in Form2 and cannot be editted? Please clarify to me. Thanks a lot guys!
Your property is an instance variable, so the value can be different across different instances of Form1.
If you are trying to access instance variables from a parent form, the easiest way to do that is to pass Form1 in to the constructor of Form2.
public partial class Form2 : Form
{
private Form1 f1;
public Form2(Form1 ParentForm)
{
InitializeComponent();
f1 = ParentForm;
}
private void Form2_Load(object sender, EventArgs e)
{
label1.Text = f1.Test;
}
}
Then when you create a new Form2 from Form1, you can do this:
Form2 frm2 = new Form2(this);
If you want your property to be read only, you can simply not specify a setter:
public string Test
{
get { return _test; }
}
Use of this method 'static'
At first Control label property Modifiers=Public
in Program code below
public static Form1 frm1 = new Form1();
public static Form2 frm2 = new Form2();
in Form1 code below
Program.frm2.show();
in Form2 code below
label1.Text=Program.frm1.text;
The frm1 not your main form object. It is newly created object where property Test initializes when it loads (in Form1_Load event handler).
The first instance of Form1 shows an instance of Form2, and then Form2 creates another instance of Form1. This could work, but you set _test in the Form.Load event, which:
Occurs before a form is displayed for the first time.
You do not show the instance of Form1 you're trying to read Test from, so its Load event will not occur and Test remains null.
You could add a constructor overload or property to pass the Form1 reference as #JohnKoerner mentions, but I would prefer to only pass the required variable, perhaps even encapsulated in an event, to reduce coupling. Form2 usually doesn't need to know all about Form1.
public
The type or member can be accessed by any other code in the same assembly or another assembly that references it.
static
The static modifier on a class means that the class cannot be instantiated, and that all of its members are static. A static member has one version regardless of how many instances of its enclosing type are created.
A static class is basically the same as a non-static class, but there is one difference: a static class cannot be externally instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself.
However, there is a such thing as a static constructor. Any class can have one of these, including static classes. They cannot be called directly & cannot have parameters (other than any type parameters on the class itself). A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced. Looks like this:
static class Foo()
{
static Foo()
{
Bar = "fubar";
}
public static string Bar { get; set; }
}
Static classes are often used as services, you can use them like so:
MyStaticClass.ServiceMethod(...);

Categories