Is there a way to make variables over forms? - c#

I have a program that has two forms in it. Is there a way that I can make a variable in Form1 show up in Form2 without having to make a class or function?
I made form2 by doing:
Form2 form2 = new Form2();
private void button1_Click(object sender, EventArgs e)
{
form2.show();
}

If you open Form2 from Form1, you can do it in several ways:
Create a constructor on Form2 that would accept a value you want to pass.
Create a property on Form2 and set it before showing Form2.
You may opt to pass a reference to Form1 (via a constructor or property) and use it in Form2 to read values of properties of Form1.

You can "share" a object between two forms is through their constructors (dependency injection).
e.g.
Form1Ctor(SharedObject obj)
Form2Ctor(SharedObject obj)
var obj = new SharedObject();
var form1 = new Form1(obj);
var form2 = new Form2(obj);

If the property is only used in a single form you could make it a static
e.g.
public static string s { get; set; }

Related

How to pull data from datagridview to another form's textbox

I am trying to pull the data from a datagridview value in form1 to a textbox in form2 .
Form 1;
public string xxx;
public string GetX()
{
return xxx;
}
private void addADocumentToolStripMenuItem_Click(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows != null)
{
xxx = dataGridView1.CurrentRow.Cells["Name"].Value.ToString();
AddDocumentForm adf = new AddDocumentForm();
adf.ShowDialog();
}
else
{
MessageBox.Show("Please choose a record.");
return;
}
}
In Form 2 trying to pull the xxx value into textbox;
using (Form1 f= new Form1())
{
string result= f.GetX();
txtSavedDocumentID.Text = result;
}
In Form2, you are creating a new instance of Form1:
using (Form1 f= new Form1())
As I can't see your whole code, I might be wrong - but I think it is very likely that this is not what you want.
What you actually want is to call GetX() on an existing instance of Form1.
Now you need some way to know the correct instance of Form1 on Form2. One easy possibility is, but only if you will always just use one instance of Form1, to expose a static property on Form1 that will provide a singleton instance of it to the outside world:
public class Form1
{
// ...
public static readonly Form1 Instance {get; private set};
public Form1()
{
Instance = this;
}
// ...
}
In Form2, instead of creating a new instance with your using statement, you'd access it like this:
string result = Form1.Instance.GetX();
txtSavedDocumentID.Text = result;
Now be aware that if your application has the possibility to have multiple instances of Form1 open, this won't work and will have bad side effects. In this case, another approach is needed. But I hope you got the idea now what might be wrong and you can work it out.
Edit: While this will solve your issue, hopefully, I want to add that it's not a very good approach having your Forms need to know about each other. You should have some model classes in the background where your Forms can read and write data on, without the need to interact with each other directly. But exploring this further would be out of scope of this question.
changed Form2 ;
public Form2(string qs)
{
InitializeComponent();
textBox1.Text = qs;
}
In Form1;
get the text from combobox and pass it to form2 ;
{
var xxxx = (cbxEmployeeName.GetItemText(cbxEmployeeName.SelectedItem));
Form2 f = new Form2(xxxx);
f.Show();
}

Empty string gets passed from one Form to another in Winforms

I have following problem:
I have a Form1 where I open a second Form2 from it. Now I have a save Button in Form2 where entries from Textboxes are saved to a csv file. But I want to save some entries from Form1 too. The Textbox entries from Form2 are getting saved but entries from Form1 are empty strings. Following code:
In Form1:
public void showInputToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2(this);
form2.Show();
}
to open the second Form via the first one and functions to grab the entries from the Form1 Textboxes:
public String getLocation()
{
return LocationBox.Text;
}
public String getFilesLoc()
{
return FilesLocation.Text;
}
In Form2 I have the following:
private Form1 m_form = null;
public Form2(Form1 f)
{
InitializeComponent();
m_form = f;
}
and then the function to grab the entries and save them:
private void button1_Click(object sender, EventArgs e)
{
Form1 form1 = new Form1();
proc.setParams(form1.getLocation(),getFilesLoc());
proc.saveCurrentSettings();
}
I left the other parameters out. So entries from Form2 are read correctly but the ones from Form1 are just an empty string (""). What can I do?
In the click handler, you're creating a new Form1 here:
Form1 form1 = new Form1();
That will have empty values - but you want the value from the existing form which you kept a reference to in your constructor - so use it!
private void button1_Click(object sender, EventArgs e)
{
proc.setParams(m_form.getLocation(), m_form.getFilesLoc());
proc.saveCurrentSettings();
}
(I'd strongly advise you to start following .NET naming conventions, quite possibly turning those get methods into properties, and also considering passing the values into your Form2 constructor instead of the Form1 reference itself. It depends on whether you need to "see" any changes made to Form1 after the construction of Form2.)
use
proc.setParams(m_form.getLocation(), m_form.getFilesLoc());
proc.saveCurrentSettings();
you are not using the reference of Form1 but creating a new object and using that.

TextBox B in Form2 to display text from TextBox A in Form 1 using C# and WinForms

After entering in the appropriate text and pressing enter, I want txtbA text in Form1 to display in txtbB in Form 2.
I already have the key events code written, but I can't seem to figure out the rest.
Visual basic seems to be more straightforward with this, and I am new to C#.
This is using WinForms.
I am really only familiar with visual basic's way of handling this:
txtbA.text = My.Forms.Form2.txbB.text
Thank you for any help you can give!
You can use a static variable
In Form1
public static string txtbAtext
{
get { return txtbAtext ; }
set {txtbAtext = value; }
}
OnTextChanged Event
txtAtext = txtA.Text;
In Form2
Form1 f1 = new Form1();
txtbB.Text = Form1.txtAText;
The simpliest and not very elegant way is to do ist like this:
Make a property in the second form, that can hold a Textbox and set the Text property in the TextChange event of the property in Form2
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public TextBox TextBoxWithSameText { get; set; }
private void textBox2_TextChanged(object sender, EventArgs e)
{
if (TextBoxWithSameText != null)
TextBoxWithSameText.Text = textBox2.Text;
}
}
All you have to do now is to set the property to the Form1.textbox1 when the second form (Form2) is created:
Form2 form = new Form2();
form.TextBoxWithSameText = textbox1;
In order to exchange strings between two Forms classes, you can use a third class. Once added to your project, you need to instantiate this new Class1 in your Form1 and Form2:
Class1 class = new Class1;
Make sure Class1 has a constructor. Now, you can create properties in your Class1, with get and set properties:
public string TextA
{
get
{
return textA;
}
set
{
textA = value;
}
}
You can then call these properties from any other class that has instantiated your Class1, like so:
class.TextA = txtbA.Text;
In order to show the text in the other textbox, you need an event to trigger changing the txtbB.Text value. You could use txtbA.ValueChanged event, or a button with a Click event. You should figure out what event is most appropriate for your project.
I hope this helped! Good luck.
Based on your comment:
Right, Form1 will open an instance of Form2 upon pressing the Enter
key. Thanks!
You can setup Form2 to receive the initial value for the TextBox via its Constructor:
public partial class Form2 : Form
{
public Form2(string InitialValue)
{
InitializeComponent();
this.txtbB.Text = InitialValue;
}
}
Then in Form1 you'd do something like:
Form2 f2 = new Form2(this.txtbA.Text);
f2.Show();

Passing tabConrol properties from on form to another

I am using two forms in a windows form application in C#.I want to pass the tabControl's properties like its "Tabpage count" from first form to second form. Can anyone help me here?I can't create object of first form in second form and call a function beacuse for a new forn object, the tabcontrol gets refreshed.
Inside your first form create an instance of your second Form class as this
Form frm= the instance of your secand form
after that show the instance of your secand form, now you exactly have an instance of your secand form inside your first form and can use all the public properties of it
You can create static public functions exposing desired control properties like in below code.
public static Color TabColor()
{
return Form1.Fom1TabControl1.SelectedTab.ForeColor;
}
and you can access Form1 properties like below;
private void Form2_Load(object sender, EventArgs e)
{
this.Fom2TabControl1.SelectedTab.ForeColor = Form1.ForeColor;
}
First Check your class accessibility and set to public if not work set public static, maybe your namespaces is different
hope it helps
This can be achieved in two ways
Aprroach 1:
Create a public variable in Form2
public int intTabCount=0;
and in Form1, you should call Form2 like
Form2 objForm2 = new Form2();
objForm2.intTabCount = tabPageCountVariable;
objForm2.Show()
Aprroach 2:
Create a parameterized constructor and public variable in Form2
public int intTabCount=0;
public Form2(int TabCounts)
{
intTabCount = TabCounts; // and use intTabCount for your class
}
and call from Form1 like
Form2 objForm2 = new Form2(tabPageCountVariable);
objForm2.Show();
Now if you want to pass value through any events like clicking an button in Form1 which updates anything in Form2, use the below link
Passing Values Between Windows Forms c#

Passing object to different windows forms

I want to pass a C# object between win forms. At the moment, I have setup a basic project to learn how to do this which consists of two forms - form1 and form2 and a class called class1.cs which contains get and set methods to set a string variable with a value entered in form1. (Form 2 is supposed to get the value stored in the class1 object)
How can I get the string value from the object that was set in form1? Do I need to pass it as a parameter to form2?
Any comments/help will be appeciated!
Thanks,
EDIT: Here's the code I have at the moment: (form1.cs)
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
Form2 form2 = new Form2();
form2.Show();
}
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
Class1 class1 = new Class1();
class1.setStringValue(textBox1.Text);
}
}
}
}
There are a few different ways to do this, you could use a static class object, the above example would be ideal for this activity.
public static class MyStaticClass
{
public static string MyStringMessage {get;set;}
}
You don't need to instance the class, just call it
MyStaticClass.MyStringMessage = "Hello World";
Console.WriteLine (MyStaticClass.MyStringMessage);
If you want an instance of the object you can pass the class object that you create on Form1 into Form2 with the following.
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
Form2 form2 = new Form2();
form2.MyClass = class1;
form2.Show();
}
Then create a property on Form2 to accept the class object.
public Class1 MyClass {get;set;}
remember to make the Class1 object a global variable rather than create it within button 2 itself.
Yes, in Form1 you declare an instance of Class1 and then set the parameters as needed, then you pass it to Form2. You could for example have a constructor in Form2 and have a Class1 parameter in it. Assuming that Form1 creates Form2, otherwise you have to have some way for Form1 to find Form2 to pass the instance across.
Since I have been working in ASP.Net the last couple years I have found myself working with Newtonsoft.Json a lot. Turns out to be great within WinForms too, and in this case seemed to simplify passing objects between forms... even complex ones are a breeze!
The implementation is like this:
// Set Object Property within Form
public partial class FlashNotify : Form
{
public string Json { get; set; }
}
On the form load event you can then grab your object:
private void FlashNotify_Load(object sender, EventArgs e)
{
// Deserialize from string back to object
CommUserGroupMessage msg = new CommUserGroupMessage();
msg = Newtonsoft.Json.JsonConvert.DeserializeObject<CommUserGroupMessage>(Json);
}
Lastly is passing the object to the form:
// Serialize the Object into a string to pass
string json = Newtonsoft.Json.JsonConvert.SerializeObject(msg);
FlashNotify fn = new FlashNotify();
fn.Json = json;
fn.Show();
Granted the original selected answer is probably easier, however I like this approach as it avoids the need to replicate the class within your form, which I think makes it easier to maintain (Correction: Miss correctly read the static class in the example, I at first thought it was replicated within the form).
Using Delegate you can easily pass data to a form.
Technically, a delegate is a reference type used to encapsulate a method with a specific signature and return type
Step 1
Add a delegate signature to form1 as below:
public delegate void delPassDataToFrom(Object obj);
Step 2
In form1’s any button click event handler, instantiate form2 class and delegate. Assign a function in form2 to the delegate and call the delegate as below:
private void btnSend_Click(object sender, System.EventArgs e)
{
Form2 frm = new Form2();
delPassDataToFrom del = new delPassDataToFrom(frm.retrieveData);
del(objectToPass);
frm.Show();
}
Step 3
In form2, add a function to which the delegate should point to. This function will use the object passed:
public void retrieveData(Object objPassedFromParent)
{
//use the objPassedFromParent object as needed
}

Categories

Resources