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
}
Related
I have form to show Customer and vendors if I open form from button1 the forms Show customer and if I open from button 2 form show vendor
the problem here I wanna the buttons open form 1 time for each I made this code but the first it work for the first opened form only and the another button open many time as much as I click the button
if (Application.OpenForms[frm.Name] != null)
{
if (Application.OpenForms[frm.Name].Text == e.Item.Caption)
{
frm = Application.OpenForms[frm.Name];
frm.BringToFront();
}
else
{
frm.Show();
}
}
else
frm.Show();
Ok, here is the code for the form that contains the buttons. I just called it Form1.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCustomer_Click(object sender, EventArgs e)
{
btnCustomer.Enabled = false;
CustomerVendorForm form = new CustomerVendorForm(btnCustomer);
form.Show();
}
private void btnVendor_Click(object sender, EventArgs e)
{
btnVendor.Enabled = false;
CustomerVendorForm form = new CustomerVendorForm(btnVendor);
form.Show();
}
And here is the CustomerVendor form:
public partial class CustomerVendorForm : Form
{
Button Form1Button;
public CustomerVendorForm(Button button)
{
InitializeComponent();
Form1Button = button;
}
private void CustomerVendorForm_FormClosed(object sender, FormClosedEventArgs e)
{
Form1Button.Enabled = true;
}
So we disable the button that they clicked. Open the form, passing the button. When the user closes the form, the button is re-enabled.
Does that make sense?
In your constructor:
btnVendor.Tag = new VendorForm();
btnCustomer.Tag = new CustomerForm();
In your button click handler (you only need one - this code will handle any number of different buttons and forms)
anyButton_Click(object sender, EventArgs e){
((sender as Control).Tag as Form).Visible ^= true;
}
--
So, your Tag is in use by some Thing already? OK, probably the easiest thing is to is make a class to hold all the things you want to put in the Tag:
class TagBucket{
public Form SomeForm { get; set; }
public Whatever OtherThing { get; set; } //you don't have to set this now, just demonstrating
}
In your constructor:
btnVendor.Tag = new TagBucket {
SomeForm = new VendorForm(),
OtherThing = new Whatever()
};
btnCustomer.Tag = new TagBucket {
SomeForm = new CustomerForm(),
OtherThing = new Whatever()
};
In your click handler:
anyButton_Click(object sender, EventArgs e){
((sender as Control).Tag as TagBucket).SomeForm.Visible ^= true;
}
well I modified my code to get open forms text and add them to string and checked if the string contain the caption of button it wont open it for second time
here is my code ,thanks for David.Warwick he give me the idea where i need to start
if (Application.OpenForms[frm.Name] != null)
{
var texts = "";
foreach (Form fr in Application.OpenForms)
{
texts += fr.Text + "/";
}
if (texts.Contains(e.Item.Caption.ToString()))
{
frm = Application.OpenForms.Cast<Form>().Where(x => x.Text == e.Item.Caption.ToString()).FirstOrDefault();;
frm.BringToFront();
}
else
{
frm.Show();
}
}
else
frm.Show();
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.
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;
}
}
}
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 Made an application. The Main form Name is Form1.
And the other Form is called PoP.
public partial class pops : Form
{
public pops()
{
InitializeComponent();
CenterToScreen();
}
private void pops_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Close();
}
private void lblAdminNo_Click(object sender, EventArgs e)
{
}
}
Make two public properties on popup form and retrieve them from parent form.
string username = string.Empty;
string password = string.Empty;
using (LoginForm form = new LoginForm ())
{
DialogResult result = form.ShowDialog();
if (result == DialogResult.Ok)
{
username = form.Username;
password = form.Password;
}
}
It all depends on from where are you calling the Pop form.
If it is called from the Form1 itself, then the Popform's object itself would provide you the value.
Pop popFrm = new Pop();
if(popFrm.ShowDialog() == Ok)
{
string userName = popFrm.TextBox1.Text;
}
If the Pop is invoked from a different area/part of application, you may have to store it somewhere common to both the forms.
This can be done through events. This approach is particularly useful when data to be posted even when the child form is kept open.
The technique is- From parent form, subscribe to a child from event. Fire the event when child form closes, to send data
----- SAMPLE CODE-----
Note: In the Parent Form add a Button:button1
namespace WindowsFormsApplication2
{
public delegate void PopSaveClickedHandler(String text);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Pops p = new Pops();
p.PopSaveClicked += new PopSaveClickedHandler(p_PopSaveClicked);//Subscribe
p.ShowDialog();
}
void p_PopSaveClicked(string text)
{
this.Text = text;//you have the value in parent form now, use it appropriately here.
}
}
Note: In the Pops Form add a TextBox:txtUserName and a Button:btnSave
namespace WindowsFormsApplication2
{
public partial class Pops : Form
{
public event PopSaveClickedHandler PopSaveClicked;
public Pops()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{
if(PopSaveClicked!=null)
{
this.PopSaveClicked(txtUserName.Text);
}
}
}
}
Summary:
1.Add a delegate(place where it available to both parent and child form) :
public delegate void PopSaveClickedHandler(String text);
2.In form:Pops, Add an event:
public event PopSaveClickedHandler PopSaveClicked;
3.Subscribe to the event in Parent Form:
p.PopSaveClicked += new PopSaveClickedHandler(p_PopSaveClicked);
4.Invoke the event in form:Pops Save Button Click
if(PopSaveClicked!=null)
{
this.PopSaveClicked(txtUserName.Text);
}
You can send data to the form object before you display it. Create a method to call, send the info through the constructor... etc.