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
Related
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.
i am working with my c# windows aplication, in this application form named "patients" and other named "patientsDuplicatedName" which contain datagridview and load all Duplicated Patients Name (this and works fine,,)
but i want when slsected Row get all values into form "patients" at run time (already open) without creating new form "Patients"..
Below is the code I am referring to:
public partial class frmPatientsNameDuplicated : Form
{
PatientFiles frmPatientsFiles =new PatientFiles() ;
public frmPatientsNameDuplicated()
{
InitializeComponent();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnOk_Click(object sender, EventArgs e)
{
frmPatientsFiles.txtFileNum.Text = this.dgvPatientsName.CurrentRow.Cells[0].Value.ToString();
frmPatientsFiles.txtArbName.Text = this.dgvPatientsName.CurrentRow.Cells[1].Value.ToString();
frmPatientsFiles.txtEngName.Text = this.dgvPatientsName.CurrentRow.Cells[2].Value.ToString();
//frmPatientsFiles.show();//this line is creating new form and run
this.Close();
}
}
sorry about my bad english & thanks in advance
The commented out line frmPatientsFiles.show() has a comment that says that the line is creating a new form. It is not. It is simply displaying a form that has been previously created on line PatientFiles frmPatientsFiles = new PatientFiles(); This appears to be creating the new form that you don't want. If you already have an existing form that you want to update, reference that form from your btnOk_Click event handler. To do this, you probably want to pass in a reference to the (existing) form to your class, either via the constructor or some other method/property. I hope I have understood your question correctly.
i found same issue here :
Pass data to a existing form
so my code become
public partial class frmPatientsNameDuplicated : Form
{
PatientFiles frmPatientsFiles = Application.OpenForms["PatientFiles"] as PatientFiles;
public frmPatientsNameDuplicated()
{
InitializeComponent();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnOk_Click(object sender, EventArgs e)
{
frmPatientsFiles.txtFileNum.Text = this.dgvPatientsName.CurrentRow.Cells[0].Value.ToString();
frmPatientsFiles.txtArbName.Text = this.dgvPatientsName.CurrentRow.Cells[1].Value.ToString();
frmPatientsFiles.txtEngName.Text = this.dgvPatientsName.CurrentRow.Cells[2].Value.ToString();
this.Close();
}
}
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.
I am writing a windows form application in c#. I changed my design to have menus. I have base class and several child class for each menu item. My problem is in my base class i am accessing a GUI element and storing its value in a public variable. now i want to access this from my child class.
public partial class x: Form
{
# calling this public method from child class to to get the variable value
public string Getlogpath()
{
Console.WriteLine(this.logpath);
return logsdirectory.Text;
}
private void reportFromLogsToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 child1 = new Form2();
this.LayoutMdi(System.Windows.Forms.MdiLayout.Cascade);
child1.Show();
}
public void browse_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.SelectedPath = (#"\\comprion02\ots\SHARED\T\COMPRION SIMfony\Log-Files");
fbd.ShowDialog();
logsdirectory.Text = fbd.SelectedPath;
logpath = logsdirectory.Text;
# this print i get value i need
Console.WriteLine(logpath);
}
}
#child form class
public partial class Form2 : Form
{
private void button1_Click(object sender, EventArgs e)
{
string data;
x obj = new x();
data = obj.Getlogpath();
#got nothing for this print
Console.WriteLine(x);
}
}
could someone help me with this.
Use this Console.WriteLine(Form.Getlogpath()); instead of Console.WriteLine(x);
Or create object of your Form class instead of X class:
Form obj = new Form();
Console.WriteLine(obj.Getlogpath());
Why don't you use the keyword protected instead of private or public. See more here - http://msdn.microsoft.com/en-us/library/wxh6fsc7(v=vs.71).aspx
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);