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

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

Related

Saving form2 from form1 button

I currently have a form called form1 that allows me to create another form called form2, form2 has a textbox that I can input text into. On form1 I have a save button to save the text in form2 as a .txt file. I am currently having issues with one of my last steps where my current method does not exist and I am not sure how to fix this without messing anything else up.
Currently I have completed the following code for my button so I can save
private void bmSaveAs_Click(object sender, EventArgs e)
{
SaveFileDialog saveText = new SaveFileDialog();
saveText.InitialDirectory = #"C:\";
saveText.Filter = "TXT Files(*.txt;)|*.txt;";
if (saveText.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (StreamWriter write = new StreamWriter(File.Create(saveText.FileName)))
write.Write(TextFile);
}
}
Now under my second form(form2) I only have the following code
public partial class TextDocumentForm : Form
{
public TextDocumentForm()
{
InitializeComponent();
}
public string TextFile
{
get { return tbTextDoc.Text; }
set { tbTextDoc.Text = value; }
}
}
My current issue lies with my public string TextFile where I get the error that the current method does not exist in Form 1. Being fairly new I am unsure as to how to proceed and would appreciate any help as I have been stumped with this for a while.
public string TextFile is a member of Form2, and of course, form1 don't know it. You can try this:
public partial class Form1 : Form
{
Form2 frm2;
public Form1()
{
InitializeComponent();
frm2 = new Form2();
}
private void ShowForm2(object sender, EventArgs e)
{
frm2.Show();
}
private void Save(object sender, EventArgs e)
{
MessageBox.Show(frm2.TextFile);
}
}

Easy Delegate ve Event issue [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
it was work before but now not working why i dont know what is the issue?
in example have 2 forms form1 have 1 button form2 have 1 textbox when start the program and click the button form1 should close, form2 open and delegate variable should write in textbox but not work. Error is "System.NullReferenceException occurred"
public partial class Form1 : Form
{
public delegate void kapatici(string al);
public static event kapatici kapat;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
kapat("deneme");
Form2 f = new Form2();
f.ShowDialog();
}
}
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
Form1.kapat += Form1_kapat;
}
private void Form1_kapat(string al)
{
textBox1.Text = al;
//throw new NotImplementedException();
}
}
I've tried different types like
private void button1_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.ShowDialog();
kapat("deneme");
}
but still not working.
thank you for your answers.
I'm not sure what you want to achieve with the code - but I think / hope it's just a minimal example. So here is a solution:
Events are null until they are suscribed. You have to check the event before you are going to invoke it:
if (kapat =! null)
{
kapat.Invoke("deneme");
}
A compact way to do this is by using the null-operator:
kapat?.Invoke("deneme");
Second mistake is to show your second form as dialog, because you are blocking your method until the dialog is closed. If your click-method looks like this, it will work:
private void button1_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.Show();
kapat?.Invoke("deneme");
}
If you only want to show a text on your second form, you should not use a event. The simplest way is to pass the string throught the constructor of the second form like:
public Form2(string al)
{
InitializeComponent();
textBox1.Text = al;
}
Now you can open the form with:
private void button1_Click(object sender, EventArgs e)
{
Form2 f = new Form2("deneme");
f.ShowDialog();
}

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.

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.

Passing data between two instantiated WinForms in C# [duplicate]

This question already has answers here:
Best way to pass data between forms using C#
(1 answer)
Transfering data from Form2 (textbox2) to Form1 (textbox1)? [duplicate]
(2 answers)
Closed 10 years ago.
I have a Main Form which dows calculations and opens and closes projects created by a user.
When the user clicks on the Open Project button under File, a form called Open Project opens as below which allows a user to load a project:
Now, I want to pass the data from this form into the main form after clicking OK.
The problem I am having is that the Main Form is already open.
Any solution to this problem would be hghly appreciated.
Try to create a Properties in Open Project Form
Main Form
private void openButton_Click(object sender, EventArgs e)
{
using(var f = new Open_Project_Form())
{
f.ProjectReference = projectRefrencetTextBox.Text;
f.ProjectNo = projectNoTextBox.Text;
f.ShowDialog();
}
}
Open Project Form
public string ProjectReference { get; set; }
public string ProjectNo { get; set; }
private void Open_Project_Form_Load(object sender, EventArgs e)
{
projectRefrenceComboBox.Text = ProjectReference;
projectNoTextBox.Text = ProjectReference;
}
UPDATE
I misinterpreted the question. My previous answer is from MainForm to OpenProjectForm this time is from OpenProjectForm to MainForm
Main Form
//Properties for MainForm
public string ProjectReference { get; set; }
public string ProjectNo { get; set; }
private void openButton_Click(object sender, EventArgs e)
{
using(var f = new Open_Project_Form() { Owner = this })
{
f.ShowDialog();
if (f.DialogResult == DialogResult.OK)
{
projectRefrencetTextBox.Text = ProjectReference;
projectNoTextBox.Text = ProjectNo;
}
}
}
Open Project Form: Take note that you have a okButton and cancelButton
private void Open_Project_Form_Load(object sender, EventArgs e)
{
okButton.DialogResult = DialogResult.OK;
this.AcceptButton = okButton;
this.CancelButton = cancelButton;
}
Now, in okButton_Click event
private void okButton_Click(object sender, EventArgs e)
{
var f = Owner as MainForm;
if (f == null) return;
f.ProjectReference = projectRefrenceComboBox.Text;
f.ProjectNo = projectNoTextBox.Text;
Close();
}
Reference:
AcceptButton
CancelButton
Button.DialogResult
Hope it will helps you.
Can you use Events? Create an EventClass and Return the value as Result of the Event.
Create an event in the opened form class:
public event EventHandler<ProjectDetailsArgs> ProjectDetailsSubmitted;
public class ProjectDetails: EventArgs
{
public string projectReference{ get; set; }
public string projectNo{get;set;}
//you can add more prop.s here
}
On your Ok button click event add
if (ProjectDetailsSubmitted != null)
{
ProjectDetailsArgs argss = new ProjectDetailsArgs();
argss.projectReference = projectRefrencetTextBox.Text;
argss.projectNo = projectNoTextBox.Text;
ProjectDetailsSubmitted(null, argss);
}
In your main form create a handler for it:
childform.ProjectDetailsSubmitted+=new EventHandler<ProjectDetailsArgs>project_detailsSubmitted);
public void project_detailsSubmitted(object sender, ProjectDetailsArgs e)
{
//Do Your work
}

Categories