C# global/public variables that keeps value - c#

I got a newbie question !
What I have is 3 windows form, named frmMain,frmSub1,frmSub2 for example.
I want a int variable which gets value from processes in frmSub or frmSub2 then used in frmMain for another process.
I explored other QA's before posting this. But none of them satisfied my curiosity. I just saw bunch of codes but I want a meaningful explonation with codes as why/how them works.
Many thanks for suggestions.
Edit :
I don't have any code for this inquiry at all. There is no application yet. I'm at planning phase. Sorry for "no code given". I can write codes after I get the stage of where I need this variable.

you can do something like this:
public class frmMain
{
public static int Vartoshare=100;
private void setvalues()
{
vartoshare=200;
}
}
then in your frmsub2 form you can call
int readvar = frmmain.vartoshare;

Solution 1: you can pass your int variable to New Form Constructor and assign that value in the NewForm constructor.
Try This:
Program.cs
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1(0));
}
Form1 Code:
int no = 10;
public Form1(int no)
{
this.no=no;
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2(no);
this.Hide();
form2.ShowDialog();
}
Form 2: Code
int no;
public Form2(int no)
{
this.no = no;
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
no = 20;
Form1 form1 = new Form1(no);
this.Hide();
form1.Show();
}
Solution 2: you can take public static varible in Form1 and access that variable in chid forms using their class names.
Try This:
Form1 Code:
public static int no = 10;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
this.Hide();
form2.ShowDialog();
}
Form 2: Code
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1.no = 20; //access Form1 int variable
Form1 form1 = new Form1(no);
this.Hide();
form1.Show();
}

Related

Getting the array length from one form class to another form class c#

I initially declare an empty public string array in my program(form1) and when a button is clicked strings in a datagridview cell is put into the array! But I find a difficulty in getting the length of that array to another form class(form2)
public partial class Form1 : Form
{
public string[] strarray;
public string order;
public Form1()
{
InitializeComponent();
}
public void button2_Click(object sender, EventArgs e)
{
var new1=dataGridView2.Rows[0].Cells[2].Value;
ordernew = new1.ToString();
strarray = ordernew.Split(',');
Form2 f2 = new Form2();
f2.Show();
}
}
The assigning string values to the array using split function is successful!
In form2 code is as follows!
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
Form1 f1 = new Form1();
for (int m = 0; m < f1.strarray.Length; m++)
{
label.Text="Hello";
}
}
}
But when I run the program I get the error "Object reference not set to an instance of an object" at the for loop of form2 ! How can I correct this?
It seems that you are initializing again the Form1.
What you can do is add another property for Form2 then assigned a value it when calling Form2.
In Form2:
public partial class Form2 : Form
{
public string[] strarray { get; set; } //add this.
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
//You can also use foreach to avoid out of bound index
foreach(var strItem in strarray)
{
label.Text = "Hello " + strItem;
}
}
}
Then when you call it in Form1
public void button2_Click(object sender, EventArgs e)
{
var new1=dataGridView2.Rows[0].Cells[2].Value;
order = new1.ToString();
Form2 f2 = new Form2();
f2.strarry = ordernew.Split(','); //surprise!! I don't know where you get ordernew variable but anyways, assign your values HERE...
f2.Show();
}
Form1 f1 = new Form1();
This is what's causing the problem. you're creating a new window not using the old one, therefore the new window still doesn't have a strarr, the easiest way to solve this with minimal changes is to make Form2 construct takes a Form1 parameter and saves it in a field then use it.
public partial class Form2 : Form
{
private Form1 _form;
public Form2(Form1 form)
{
InitializeComponent();
_form = form;
}
private void Form2_Load(object sender, EventArgs e)
{
for (int m = 0; m < _form.strarray.Length; m++)
{
label.Text="Hello";
}
}
}
And in the event handler of Form1 you'll pass this as parameter:
Form2 f2 = new Form2(this);
f2.Show();
P.S: that's just one way with minimal changes, I don't encourage using it much as it can get confusing on larger scales.

Sending variables from Form2 to Form1 [duplicate]

This question already has answers here:
Communicate between two windows forms in C#
(12 answers)
Closed 1 year ago.
I wanna know how I can send variables from Form2 to Form1. I have one textbox and button in Form1 and one textbox and button in Form2. My application starts at Form1, textbox1 is empty and by clicking button Form2 will appear. In Form2 I want to write number and by clicking on the button send it to Form1 textbox.
I was trying this code, but I dont know how to solve it.
Form1 code:
public static int number;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form = new Form2();
form.Show();
}
Form2 code
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1.number = textBox1.Text;
this.Visible = false;
}
Now I have variable called number in Form1, which contains value of Form2 Textbox, right? But how do I say: textbox1.text(Form1) = number after that action? Do I need refresh Form1 somehow?
Thanks!
I'd say a nice easy way to do this kind of thing, is via making a public event:
In form two, add an event:
public partial Class Form2
{
public event Action<string> SomethingHappened;
...
We need to fire the event on Form2 - to notify subscribers:
//On Form2
private void button1_Click(object sender, EventArgs e)
{
if(SomethingHappened != null)
SomethingHappened (textBox1.Text);
}
Then, upon creation 'subscribe' the parent form Form1 to action on the sub-form:
Form2 form = new Form2();
//Here, we assign an event handler
form.SomethingHappened += (string valueFromForm2) =>
{
//Event handled on Form1
this.Number = valueFromForm2;
};
The setup sounds kinda like a settings dialog where you can't continue in Form1 until Form2 is closed.
If this is the case, then something more like his would be appropriate in Form1:
public partial class Form1 : Form
{
private int number = 411;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.textBox1.Enabled = false;
this.textBox1.Text = number.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(this.number);
if (f2.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.number = f2.Number;
this.textBox1.Text = this.number.ToString();
}
}
}
With Form2 looking something like:
public partial class Form2 : Form
{
public Form2(int number)
{
InitializeComponent();
this.textBox1.Text = number.ToString();
}
private int number = 0;
public int Number
{
get { return this.number; }
}
private void btnOK_Click(object sender, EventArgs e)
{
int value;
if (int.TryParse(this.textBox1.Text, out value))
{
this.number = value;
this.DialogResult = System.Windows.Forms.DialogResult.OK;
}
else
{
MessageBox.Show(textBox1.Text, "Invalid Integer");
}
}
}

Disable timer from another form in c#

Hello I am following this post Control timer in form 1 from form 2, C# , response, the problem is that I can not solve it yet, I have a timer on form1, and I need to stop it from form2 try all that I found in this post but still nothing.
Form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
richTextBox1.AppendText("test\n");
}
}
Form2
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
//
}
private void button1_Click(object sender, EventArgs e)
{
Form1 form1 = new Form1();
form1.Hide();
form1.timer1.Enabled = false;
}
}
anyone can help me ?
Update :
static class Program
{
/// <summary>
/// Punto de entrada principal para la aplicaciĆ³n.
/// </summary>
[STAThread]
public static Form1 MainForm;
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
The problem is that you are creating a new instance of Form1, so that is a different timer than the instance of the form you are looking at. You need to store a reference to the Form1 that is displayed (probably in your Program.Main).
So your Program.Main probably looks like this:
static class Program
{
public static int Main()
{
Form1 form = new Form1();
Application.Run(form);
}
}
You want to store that reference, so modify it as such:
static class Program
{
public static Form1 MainForm;
[STAThread]
public static int Main()
{
MainForm = new Form1(); // THIS IS IMPORTANT
Application.Run(MainForm);
}
}
And then you can use that stored referene in your Form2:
private void button1_Click(object sender, EventArgs e)
{
Program.MainForm.Hide();
Program.MainForm.timer1.Enabled = false;
}
This is a functional solution - personally I would not consider this an optimal solution. I would look at using something along the lines of an Event Aggregator/Broker, but if this is a really simple program without a lot of need for complexity, then this works.
Make sure the timer you need to access is modified as public, because the default modifier will be private.
Use the Properties panel provided by your IDE or use the designer code.
public System.Windows.Forms.Timer timer2;

Passing values from one form to another form in c# [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have 2 forms.
I do something wrong when I pass text from form 2 to form 1.
My textbox2 from form 2 doesn't change in my initial form1(are created another form1) when I click on the button, how can I solve it? I want to have only 2 forms, no more.
Code:
public partial class Form1 : Form
{
private string vas;
public Form1()
{
InitializeComponent();
}
public string backsend
{
get { return vas; }
set {vas = value; }
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.passValue = textBox1.Text;
f2.Show();
}
}
public partial class Form2 : Form
{
private string Mn;
public string passValue
{
get { return Mn; }
set { Mn = value; }
}
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
textBox2.Text = Mn;
}
private void button2_Click(object sender, EventArgs e)
{//click for clear textbox1 from form 2.
textBox2.Clear();
}
private void button1_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1(); i don't understand why is created another form,but not variable
f1.backsend = textBox2.Text;
f1.textBox2.Text = f1.backsend; //no exchange in my first form 1
MessageBox.Show(f1.textBox2.Text);//it's correct
}
}
You've already detected the mistake, the line
Form1 f1 = new Form1(); i don't understand why is created another form,but not variable
This creates a new instance of the class Form1 which you've not shown anywhere, nor do you want to.
What you want to do is change the value on the already instantiated and shown form. You can do this by passing the reference to your instantiated Form1 to your f2.
Change this code
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.passValue = textBox1.Text;
f2.Show();
}
to
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.initatorForm = this;
f2.passValue = textBox1.Text;
f2.Show();
}
and add the appropriate property for initatorForm or you can just use .Parent in your Form2 since the parent should be the form you used to show the form, but I'm not 100% on that.
Also, this way you've done you are only changing the variable vas but not the value of the textbox. You could add that to the setter if you like.
I think this example will helped you:
This example will use the string input from Form1 to Form2:
public partial class Form1 : Form
{
private string vas;
public Form1()
{
InitializeComponent();
}
public string Test { get;set; }
private void button1_Click(object sender, EventArgs e)
{
Test = textBox1.Text;
Form2 f2 = new Form2(this);
f2.Show();
}
}
public partial class Form2 : Form
{
private Form1 form1;
public Form2(Form1 parentForm)
{
InitializeComponent();
form1 = parentForm;
}
private void Form2_Load(object sender, EventArgs e)
{
//you can use the public string from Form1 here like this:
textBox1.Text = form1.Test;
}
}

Pass a variable from an open form C#

I have two forms, Form1 and Form2. Form1 has a variable int x. When the program is executed, Form1 is hidden and Form2 is shown; however i need to call the variable from the existing Form1.
I know the method to call the variable by calling a new instance of Form1.
Form1 r = new Form1();
r.x = 20;
But I want to know how to do it for an already opened Form1.
Take several cases, like if there are multiple variables that are called from Form1, by several forms (Form2, Form3, Form4 etc...). Any variable can be called from Form1 by the forms. Also, forms can call variables from other forms (Like if Form1 and Form2 is open, then Form3 can call variables from Form1 AND Form2)
I know its a huge list, but would really appreciate if anyone can find a good way to implement it.
You will have to have a reference to the "already opened" form1 instance, so that you can reference the value of x on that form.
So, lets say that Form2 instantiates the hidden form1. You will have to have a reference in form2 to the form1, to reference the variable.
OK, Lets say this is the code for form2
public partial class Form2 : Form
{
private Form1 f;
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
f = new Form1
{
Visible = false
};
int x = f.X;
}
}
and then code for form1
public partial class Form1 : Form
{
public int X { get; set; }
public Form1()
{
InitializeComponent();
X = 20;
}
}
and you need to ensure that the form luanched from the program class is
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form2());
}
}
You can do it in following ways,
in my case form1 is form4 and form2 is form5. please consider, :)
//code on form4:
// this is by passing the reference of the form to other form
public partial class Form4 : Form
{
public int a { get; set; }
public int b { get; set; }
public Form4()
{
InitializeComponent();
}
private void Form4_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
a = 5;
b = 6;
Form5 frm5 = new Form5();
frm5.frm4 = this;
this.Close();
frm5.Show();
}
}
// code on form5
public Form4 frm4 { get; set; }
private void Form5_Load(object sender, EventArgs e)
{
int x = frm4.a;
int y = frm4.b;
}
Also you can have a class file in which the instance of the form1 will be static, so that you can use that instance on form2 to refer to the form1's properties.
Let me know, if it does not solve your problem.
I hope it will help you. :)
Create a public property on the form itself. Have the get accessor return the form value. You can call it like this. Form1.MyProperty;
public string MyPrperty {
get {
return Form1.txtExample.text;
}
}
EDIT:
You can return a dictionary of all of those values if you have that many to return at a time. I would seriously consider rethinking your form if you have 20-40 values being filled. That sounds like a poor user experience to me.
i think there is a reason that you wouldn't try System.Properties.Settings.Default
accessible from Project Menu --> Properties in visual studio...
Thanks...
My guess is that you are looking for System.Windows.Forms.Application.OpenForms property which holds all the open forms in an array.
What you need to do is to check the type of each form and if it is equivalent to Form1 access the variable's value. Also, to access the variable outside the form you need to set its access modifier to either Public or make a corresponding property for it.
EDIT
Here is a sample code: (untested)
public partial class Form1 : Form
{
public int X;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
X = 100;
Form2 frm = new Form2();
frm.Show();
this.Hide();
}
}
public partial class Form2 : Form
{
int local_X = 0;
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
foreach(Form f in System.Windows.Forms.Application.OpenForms)
{
if(typeof(f) == typeof(Form1))
{
local_X = f.X; // access value here and set in local variable
}
}
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Value of X is : " + local_X); // Show alert for value of variable on button click
}
}
EDIT
Or you can use constructor overloading to accomplish this task:
public partial class Form1 : Form
{
public int X;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
X = 100;
Form2 frm = new Form2(x); // pass variable to form2, if multiple values pass int array
frm.Show();
this.Hide();
}
}
public partial class Form2 : Form
{
int local_X = 0;
public Form2()
{
InitializeComponent();
}
// Overloading of constructor
public Form2(int X) // if multiple values pass int array
{
InitializeComponent();
local_X = x; // capture value from constructor in class variable.
}
private void Form2_Load(object sender, EventArgs e)
{
// no need to iterate here for now due to overloading value get passed during initialization.
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Value of X is : " + local_X); // display value if alert box.
}
}
Let's look at the situation.You have multiple forms in your application and you want to do access several variables these forms.
My guess is,
public static class GlobalVariables
{
public static object MyVariable1 { get; set; }
public static object MyVariable2 { get; set; }
}
So you can access variables everywhere in your project.
It doesn't matter whether which form is opened or closed. Your ultimate goal is to access a member from Form1 in Form2 isn't it? If that is the case when you create an instance of your Form2, do it like this
Form1 objForm1 = new Form1();
Form2 obj = new Form2(objForm1);
so that in form 2 class looks like this
class Form2: Form
{
private Form1 form1Object;
public Form2(Form1 obj)
{
form1Object = obj;
}
private void SomeMethodInForm2()
{
//Here you can access the variable in form1 like
form1Object.PropertyNameYouWantToAccess;
}
}
The form 1 class can look like this
class Form1: Form
{
public int PropertyNameYouWantToAccess{get;}
}

Categories