Passing Values Between Windows Forms c# [duplicate] - c#

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.

Related

Call another form functions from the first form

I hope the title is clear enough. Let me explain : I am doing a c# Winform App. When I start the app I have my Form 1 which starts, and I have other forms I can open from it by clicking buttons.
The problem is, I have functions in those Forms (Form 2, Form 3, Form 4..) I want to start from the Form 1 .
Currently here's my code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// First Event, when I click in the toolstrip menu, I open the Form2 ("Ligne3")
private void ligne3ToolStripMenuItem_Click(object sender, EventArgs e)
{
var Ligne3 = new Ligne3();
Ligne3.Show();
}
Then, I have components in the Form2 (textboxs, buttons, functions etc)
public partial class Ligne3 : Form
{
public Ligne3()
{
InitializeComponent();
}
private void Ligne3_Load(object sender, EventArgs e)
{
//Some code
}
}
//Function I want to call from the Form1
public void send_email()
{
//Some code
}
How can I start my " send_email() " function from the Form1 (for example during Load Event) ?
Assign the values of Form2 or any other objects/variables to Linge3 object before calling show. Values which are needed in send_email() to be assigned before calling send_email(). Something like below.
private void ligne3ToolStripMenuItem_Click(object sender, EventArgs e)
{
var ligne3 = new Ligne3();
//define variables/properties in Ligne3 for all values to be passed
//then assign them with corresponding values
ligne3.Value1 = objForm2.Value1;
ligne3.Value2 = objForm2.Value2;
ligne3.Value3 = objForm2.textBox1.Text;
ligne3.Value3 = objForm2.checkBox1.Value;
//and so on
ligne3.send_email();
ligne3.Show();
}
If you are clicking a buttons on Form1, to start and open forms 2,3,4 etc, and in those btn_click handlers you are creating a new form2, 3,3,4. Then you will have a reference to each form and and can therefore just call the respective public method on the instance just created. eg
public class Form1
{
private Form2 subForm2;
private void OpenForm2_Click(object sender, eventargs e)
{
subForm2 = new Form2();
subForm2.Show()
}
private void sendEmailBtn_Click(object sender, EventArgs e)
{
subForm2.Send_email();
}
}
This are many things wrong with the above from a design point of view but i'm just using it to present the idea.
If you are creating the instance of Form2,3,4 etc outside of Form1's instantiation, then you would need some form of Constructor or property injection to provide the instance references.

how to pass datagridview value to another form

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();
}
}

How can I clear a TextBox in Form1 from Form2? C# [duplicate]

This question already has answers here:
How to access a form control for another form?
(7 answers)
Closed 7 years ago.
I have a TextBox (let's call it textBox1) inside Form1. When the user presses "New" to clear the screen, after accepting that their work will be lost (from within Form2), how do I make textBox1 clear? I can't access it directly from the second form and I can't think of a feasible way to do this.
Thanks in advance for the help!
Add a public flag of success in a Form2 and check it afterwards. Or you can use built-in functionality of ShowDialog and DialogResult.
It is more proper in terms of OOP and logic than changing the value of Form1 from a Form2.
If you change the value of hardcoded form then you will be unable to reuse this form again.
With this approach you can reuse this form again in any place.
Using simple custom variable:
public class Form2 : Form
{
public bool Result { get; set; }
public void ButtonYes_Click(object sender, EventArgs e)
{
Result = true;
this.Close();
}
public void ButtonNo_Click(object sender, EventArgs e)
{
Result = false;
this.Close();
}
}
public class Form1 : Form
{
public void Button1_Click(object sender, EventArgs e)
{
using (Form2 form = new Form2())
{
form.ShowDialog();
if (form.Result) TextBox1.Text = String.Empty;
}
}
}
Using DialogResult or ShowDialog:
public class Form2 : Form
{
public void ButtonYes_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Yes;
this.Close();
}
public void ButtonNo_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.No;
this.Close();
}
}
public class Form1 : Form
{
public void Button1_Click(object sender, EventArgs e)
{
using (Form2 form = new Form2())
{
var result = form.ShowDialog();
if (result == DialogResult.Yes) TextBox1.Text = String.Empty;
}
}
}
It also a good idea to use using as form is not disposed after ShowDialog.
It makes disposing deterministic. This way you can ensure it is disposed right after you stopped using it.

Transfer value from Form2 to Form1 in C# [duplicate]

This question already has answers here:
Communicate between two windows forms in C#
(12 answers)
Closed 3 years ago.
I have 2 winforms in my project. When i clicked on "Settings" button on Form1, it shows the Settings form, I'm making some changes on textboxes and when I click the Save button on second form, it saves these values to a text file and I wanna pass these values to first form, but I couldn't pass them.
Here is some parts of my codes;
This code is Settings button click (on Form1)
private void button3_Click(object sender, EventArgs e)
{
Settings frm = new Settings();
frm.Show();
}
public void funData(TextBox txtForm1)
{
label3.Text = txtForm1.Text;
}
and this code is Save button click (Second form)
private void button5_Click(object sender, EventArgs e)
{
if (File.Exists(ConfigFile))
{
File.Delete(ConfigFile);
using (StreamWriter writer = new StreamWriter(ConfigFile))
{
writer.WriteLine(txtTemsPath.Text);
writer.WriteLine(txtVodafonePath.Text);
writer.WriteLine(txtTurkcellPath.Text);
writer.WriteLine(txtAveaPath.Text);
writer.Close();
}
}
else
{
using (StreamWriter writer = new StreamWriter(ConfigFile))
{
writer.WriteLine(txtTemsPath.Text);
writer.WriteLine(txtVodafonePath.Text);
writer.WriteLine(txtTurkcellPath.Text);
writer.WriteLine(txtAveaPath.Text);
writer.Close();
}
}
Form1 frm = new Form1();
delPassData del = new delPassData(frm.funData);
del(this.txtTemsPath);
frm.getSettings();
frm.TemsPath = TemsPath;
frm.Activate();
frm.Refresh();
this.Close();
}
Could you please help me for this issue?
Thanks
define on your first Form:
Settings obj = (Settings)Application.OpenForms["Settings"];
private void button3_Click(object sender, EventArgs e)
{
Settings obj = new Settings();
obj.Show();
}
And replace in your code anywhere else frm with obj
The thing is that you must refer each time to the current instance of the other form and not open a new one
You need to create a public property accessor on form2 with the data you would like to store. After form2 closes you will still be able to access this data by using form2.MySpecialData as long as you havent nullified it. this question has been asked many times on stackoverflow and there are alot of good examples.
Communicate between two windows forms in C#
public Form2()
{
InitializeComponent();
}
private string mySpecialData;
public string MySpecialData
{
get { return mySpecialData; }
set { mySpecialData = value; }
}
Add a property to Settings to return the "TemsPath" value. Then, instead of Close(), set DialogResult to OK:
public partial class Settings : Form
{
public string TemsPath
{
get { return txtTemsPath.Text; }
}
private void button5_Click(object sender, EventArgs e)
{
// ... your save code ...
this.DialogResult = System.Windows.Forms.DialogResult.OK;
}
}
Now, back in Form1, use ShowDialog() instead of Show() and access the property when it returns:
public partial class Form1 : Form
{
private void button3_Click(object sender, EventArgs e)
{
Settings frm = new Settings();
if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
label3.Text = frm.TemsPath;
}
}
}

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

Categories