Passing values through forms c# - c#

I am building a form application at Visual Studio 2015 in C#. First of all i've made a user login form using 2 textboxes and 1 button. All i want to do is to pass the value from the textbox that contains username to a label which is located to another form which form is called MainMenu. This is my code for the button i made to the login form:
private void button_login(object sender, EventArgs e)
{
MainMenu username = new MainMenu();
username.Value1 = textBox1.Text;
this.Hide();
MainMenu ss = new MainMenu();
ss.Show();
}
and the code for the MainMenu form that i want to pass the value is the following:
private string value1 = string.Empty;
public string Value1
{
set { value1 = value; }
get { return value1; }
}
private void MainMenu_Load(object sender, EventArgs e)
{
label7.Text = Value1;
}
As you can see i have create a property in MainMenu form that is accessible from login form so i could transfer the value from textbox1 directly in your MainMenu form. The problem is that the text in label7 remains empty during runtime and i can't understand why. Am i missing something from my code or i am doing something completely wrong ?
Any suggestions would be appreciated

You actually create two Forms: username and ss. You set Value1 of username, but you show ss which you didn't set its Value1. So you should show username:
private void button_login(object sender, EventArgs e)
{
MainMenu username = new MainMenu();
username.Value1 = textBox1.Text;
this.Hide();
username.Show(); // and not ss.Show();
}
Also, a tip, use better names for your variables. The code below do exactly the same thing but is much more comprehensible:
private void loginButton_Click(object sender, EventArgs e)
{
var mainMenuForm = new MainMenu();
mainMenuForm.UserName = userNameTextBox.Text;
this.Hide();
mainMenuForm.Show();
}
class MainMenu : Form
{
// This is an "Auto-Implemented Property".
// Auto-Implemented Properties are used as a shortcut of what you have done.
// Google them for more information.
public string UserName { get; set; }
private void MainMenu_Load(object sender, EventArgs e)
{
userNameLabel.Text = UserName;
}
}

MainMenu username and MainMenu ss are two distinct instances (of the same MainMenu class, but that's a detail).
You are setting the memeber variable Value1 of username instance but you are displaying ss instance.
Consider this code
private void button_login(object sender, EventArgs e)
{
MainMenu username = new MainMenu();
username.Value1 = textBox1.Text;
this.Hide();
usename.Show();
}

You are using two different MainMenu objects, the right code should be something like
MainMenu username = new MainMenu();
username.Value1 = textBox1.Text;
this.Hide();
username .Show();

Just as a completely different approach to the problem:
Another option is to create a static class in your project that will house any variables that you would like to reuse.
So lets say your static class is call Globals, after successfull login you would set the variable you require ie Globals.Username = textBox1.Text.
Then wherever you need that value again you can access it using Globals.Username.

When you need to pass variable values from one form to another, write the constructor of the second form accordingly and pass the value while creating the object of the second form.
private void button_login(object sender, EventArgs e)
{
MainMenu ss= new MainMenu(textBox1.Text);
this.Hide();
ss.Show();
}
class MainMenu : Form
{
// This is an "Auto-Implemented Property".
// Auto-Implemented Properties are used as a shortcut of what you have done.
// Google them for more information.
public string UserName { get; set; }
private void MainMenu(string userName)
{
this.UserName = userName;
}
}
Creating public properties and accessing them in another class for every instance of the class is bad practice for OOP.

Related

pass a value from one form to another

I have two forms, and I need pass a value from form1.textbox1 to form2.variable
Form1:
string Ed = "", En = "";
public string En1
{
get { return En; }
set { En = value; }
}
public string Ed1
{
get { return Ed; }
set { Ed = value; }
}
private void button1_Click(object sender, EventArgs e)
{
Form2 F2 = new Form2();
F2.Show();
F2.textbox1value = Ed;
F2.textbox2value = En;
}
`
and Form2:
public string textbox1value
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
public string textbox2value
{
get { return textBox2.Text; }
set { textBox2.Text = value; }
}
private void button1_Click(object sender, EventArgs e)
{
Form1 F1 = new Form1();
F1.Ed1 = textBox1.Text;
F1.En1 = textBox2.Text;
}
when I click "save" on form2 and open debug I see "ed = 3; en = 5", but when i click "open form2" on form1 and open debug, i see "Ed = null; En = null;" and shows a blank form without value in textboxes. help please.
You create a new form, so old values will be lost. Default values are null.
Form1 F1 = new Form1(); //I'm a new Form, I don't know anything about an old form, even if we are the same type
You can use static vars, which would be the easiest solution to archive your goal, but there are other ways like constructors, containers, events etc.
public static string En1
{
get { return En; }
set { En = value; }
}
public static string Ed1
{
get { return Ed; }
set { Ed = value; }
}
And in the other form
private void button1_Click(object sender, EventArgs e)
{
Form1 F1 = new Form1();
Form1.Ed1 = textBox1.Text;
Form1.En1 = textBox2.Text;
}
Please be advised that a static variable exists only once for a class. So if you have multiple instances and you change the static variable in one, the change also affects all other instances.
You can create constuctor for form2 which accept 2 arguments and access these variables
Form2 frm2 = new Form2(textBox1.Text,textBox2.Text);
frm2.Show();
Constructor would look like
public Form2(string txt1,string txt2)
{
InitializeComponent();
textbox1value.Text = txt1;
textbox1value.Text=txt2
}
There are many ways to pass data between forms such as
1) Using constructor
2) Using objects
3) Using properties
4) Using delegates
Check this link for details http://www.codeproject.com/Articles/14122/Passing-Data-Between-Forms
Hope It helps!
The debugger doesn't complain about anything? Hm.
Maybe you could try to modify your button1_click method in form 1 as follows:
private void button1_Click(object sender, EventArgs e)
{
Form2 F2 = new Form2();
Form2.Parent = this;
F2.Show();
F2.textbox1value = F2.Parent.Ed;
F2.textbox2value = F2.Parent.En;
}
Always keep a copy of the information of form2 in form1, this is:
When the user clicks save on form2 the information go in the local variables of form2 and then form2 runs an Event (telling form1 that its information must be saved). In form1 you handle this event and tell form1 that whenever this event is run from1 must copy the information of form2 into itself.
On the other hand when ever you are opening form2 again you should first give the information back to it and then execute the show() method. After this you should handle the shown() event of form2 in the way that whenever it is shown, first form2 must put the information it has to the related textboxes, etc ... .
This can be achieved easily by creating an instance of Form 1 in Form 2. This is one of the approach.
Follow the steps:
In Form 1 : Make sure that your control is public.
eg: txtForm1.Text = "Bangalore";
In Form 2 :
Step 1: Create an instance of Form 1 globally. If the instance is created locally the value contained by the control cannot be accessed, only null value will be returned even the data has been populated to it.
Step 2 : Retrieve the control's value by Form 1's instance.
eg: Form1 frm1 = new Form1();
string Form1Value = frm1.txtForm1.Text
If you describe value as static then you can access it directly
in Form1 and you can access it from Form2 :
static public string Text_;
string PassedValue_=Form1.Text_;
This question may be old, but anyways...
Another way to do it is, to have a constructor in form2 that accepts an argument of the same type of the data you want to pass to, and, when button in form1 is clicked, you create the instance of form2 using the constructor that accepts the argument, and pass the data to it.
//Form1
Form2 form2;
button1_clic(object sender, eventArgs e)
{
form2 = new Form2(textbox1.text);
form2.Showdialog();
}
//Form2
string var = string.empty;
public Form2(string val)
{
InitializeComponents();
var = val;
}

Passing Values Between Windows Forms c# [duplicate]

This question already has answers here:
Communicate between two windows forms in C#
(12 answers)
Closed 3 years ago.
I am struggling to work out how to pass values between forms. I have four forms and I want to pass the information retrieved by the Login to the fourth and final form.
This is what I have so far.
In this function:
private void btnLogin_Click(object sender, EventArgs e)
I have deserialized the data I want like this:
NewDataSet resultingMessage = (NewDataSet)serializer.Deserialize(rdr);
Then, when I call the next form I have done this:
Form myFrm = new frmVoiceOver(resultingMessage);
myFrm.Show();
Then, my VoiceOver form looks like this:
public frmVoiceOver(NewDataSet loginData)
{
InitializeComponent();
}
private void btnVoiceOverNo_Click(object sender, EventArgs e)
{
this.Close();
Form myFrm = new frmClipInformation();
myFrm.Show();
}
When I debug, I can see the data is in loginData in the second form, but I cannot seem to access it in the btnVoiceOverNo_Click event. How do I access it so I can pass it to the next form?
You need to put loginData into a local variable inside the frmVoiceOver class to be able to access it from other methods. Currently it is scoped to the constructor:
class frmVoiceOver : Form
{
private NewDataSet _loginData;
public frmVoiceOver(NewDataSet loginData)
{
_loginData = loginData;
InitializeComponent();
}
private void btnVoiceOverNo_Click(object sender, EventArgs e)
{
// Use _loginData here.
this.Close();
Form myFrm = new frmClipInformation();
myFrm.Show();
}
}
Also, if the two forms are in the same process you likely don't need to serialize the data and can simply pass it as a standard reference to the form's constructor.
Google something like "C# variable scope" to understand more in this area as you will encounter the concept all the time. I appreciate you are self-taught so I'm just trying to bolster that :-)
In various situations we may need to pass values from one form to another form when some event occurs. Here is a simple example of how you can implement this feature.
Consider you have two forms Form1 and Form2 in which Form2 is the child of Form1. Both of the forms have two textboxes in which whenever the text gets changed in the textbox of Form2, textbox of Form1 gets updated.
Following is the code of Form1
private void btnShowForm2_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.UpdateTextBox += new EventHandler<TextChangeEventArgs>(txtBox_TextChanged);
form2.ShowDialog();
}
private void txtBox_TextChanged(object sender, TextChangeEventArgs e)
{
textBox1.Text = e.prpStrDataToPass;
}
Following is the code of Form2
public event EventHandler<TextChangeEventArgs> UpdateTextBox;
private string strText;
public string prpStrText
{
get { return strText; }
set
{
if (strText != value)
{
strText = value;
OnTextBoxTextChanged(new TextChangeEventArgs(strText));
}
}
}
private void textBox_Form2_TextChanged(object sender, EventArgs e)
{
prpStrText = txtBox_Form2.Text;
}
protected virtual void OnTextBoxTextChanged(TextChangeEventArgs e)
{
EventHandler<TextChangeEventArgs> eventHandler = UpdateTextBox;
if (eventHandler != null)
{
eventHandler(this, e);
}
}
In order to pass the values we should store your data in a class which is derived from EventArgs
public class TextChangeEventArgs : EventArgs
{
private string strDataToPass;
public TextChangeEventArgs(string _text)
{
this.strDataToPass = _text;
}
public string prpStrDataToPass
{
get { return strDataToPass; }
}
}
Now whenever text changes in Form2, the same text gets updated in textbox of Form1.

Transfer datafrom one form to an other

I have a C# application with two forms(form1,form2).In form1 on btnTransfer_click I open second form.
private void btnTransfer_Click(object sender, EventArgs e)
{
Form2 frmConn = new Form2 ;
frmConn .Show();
//i need here values from second form
}
In second form I have 2 textboxes (txtUser,txtPassword) and a button (btnOk) .On button btnOk I verify user and password and if are correct i have to come back to first form and get this values on click button.
In Form2 :
private void btnOk_Click(object sender, EventArgs e)
{
//verify if txtUser and txtPassword are correct
//if are corrects i have to send back to first form
this.Close();
}
How can I do This?
Thanks!
In the class for form2, create two public class properties, one for the value of each textbox:
private String _username = null;
public String UserName { get { return _username; } }
private String _password = null;
public String Password { get { return _password; } }
In form2 you can verify and assign to properties:
private void btnOk_Click(Object sender, EventArgs e)
{
//verify if txtUser and txtPassword are correct
if (correct)
{
_username = txtUser.Text;
_password = txtPassword.Text;
}
this.Close();
}
Then you can retrieve them in your form1 code as such:
private void btnTransfer_Click(Object sender, EventArgs e)
{
//This using statement will ensure that you still have an object reference when you return from form2...
using (Form2 frmConn = new Form2())
{
frmConn.Show();
String user = frmConn.UserName;
String pass = frmConn.Password;
if (!String.IsNullOrEmpty(user) && !String.IsNullOrEmpty(pass))
//do something with them, they are valid!
}
}
Usually, it's using a Data Transfer Object:
http://msdn.microsoft.com/en-us/library/ff649585.aspx
Or a Domain Object.
http://msdn.microsoft.com/en-us/magazine/dd419654.aspx

Passing a Binary Search Tree between forms

I'm currently trying to access a binary search tree I created in form1 within form2. My code for the first form is:
public Home() {
InitializeComponent();
}
AddArtist secondForm = new AddArtist();
BSTree<Artist> ArtistCollection = new BSTree<Artist>();
private void btnAdd_Click(object sender, EventArgs e) {
secondForm.ShowDialog();
}
The code for my second form is:
private void btnDone_Click(object sender, EventArgs e) {
string artistName = txtName.Text;
Artist newArtist = new Artist(artistName);
ArtistCollection.InsertItem(artistName);
this.DialogResult = DialogResult.OK;
}
I've tried the method of declaring it within its own class so no results.
Just expose ArtistCollection as a property in your first form.
public BSTree<Artist> ArtistCollection { get; set; }
You can then refer to it from your second form like this:
var tree = form1.ArtistCollection;
Or, create a new constructor in Form2
public Form2(BSTree<Artist> artistCollection)
{
this.artistCollection = artistCollection;
}
when instantiating the second form they must first pass with "this" with which they must deal with in the constructor of the second form

Visual C# - Access instance of object created in one class in another

I apologize in advance with what will probably be a fairly easy/quick answer based on scope, but I've looked everywhere and am surprised to not come up with an answer.
I have created a class called Soldier with roughly 100 class variables. I need a user to enter information and gradually build a Solider object over the course of several different class Forms (because there is too much data to collect on just one).
I create an (empty) instance of a Soldier (tempSoldier) in Form1.cs and start to set the object's class variables that I collect from the user.
private void button1_Click(object sender, EventArgs e)
{
Soldier tempSoldier = new Soldier();
tempSoldier.surname = textbox1.text;
}
My question: how do I gain access to the object instance (tempSoldier) from Form1.cs in the other classes (Form2.cs, Form3.cs ...)?
I should mention that all of the Forms (Form1.cs, Form2.cs ...) share the same namespace.
Thanks in advance
Edit: All solutions below work so it just depends upon which one you like the best. Thank you for your feedback.
One little note, make sure you make ALL of the class modifiers Public including your custom class (in my case Soldier.cs).
You'll need to declare the Soldier instance in in a higher scope.
One way of doing this would be to declare it inside Form1, then pass it to Form2, and so on.
public class Form1
{
private Soldier tempSoldier = new Soldier();
private void button1_Click(object sender, EventArgs e)
{
tempSoldier = new Soldier();
tempSoldier.surname = textbox1.text;
}
private void GotoNextStep()
{
// pass the existing instance to the next form
Form2 form2 = new Form2(tempSoldier);
// display form 2 ...
}
}
Another possibility is to use a singleton variable in a class that all the forms have access to.
public class MyAppManager
{
private static readonly Soldier _soldier = new Solider();
public static Soldier SoldierInstance
{
get { return _soldier; }
}
}
private void button1_Click(object sender, EventArgs e)
{
MyAppManager.SoldierInstnace.surname = textbox1.text;
}
The former approach is ok if there's a distinct sequence to the forms; the latter is better if difference forms could be used at different times or revisited.
You can also make Soldier a static variable :
public static Soldier soldier {get;set;}
private void button1_Click(object sender, EventArgs e)
{
soldier = new Soldier();
soldier.surname = textbox1.text;
}
Code in other forms:
Form1.soldier.name ="";
You should create a public property on your form that exposes the soldier. You can then access this property from the other forms.
// ...
public Soldier Soldier { get; private set; }
private void button1_Click(object sender, EventArgs e)
{
Soldier tempSoldier = new Soldier();
tempSoldier.surname = textbox1.Text;
this.Soldier = tempSoldier;
}
// ...
Your Form2 class could look something like this:
public partial class Form2
{
private Form1 form1;
public Form2(Form1 form1)
{
this.form1 = form1;
this.InitializeComponent();
}
public void DoStuffWithForm1()
{
// ...
string surname = this.form1.Soldier.surname;
// ...
}
}
In your other class, create a method with objects as parameters.
public class TryMe (TextBox newTextbox) {
newTextbox.Text = "Hello this is a text."
//You can also get the value of textbox of another form
var textString = newTextbox.Text;
}
And then in your main form, call that method with your objects as parameters. In this case, add textbox1 to your method's parameter.
Your code in form:
TryMe(textbox1);

Categories