So, I have two forms -- one that is open, and another that is essentially just a popup on the second one. The second form opens with a maskedtextbox inside it, plus Save and Cancel buttons -- I want Save to change a field on the first form.
As far as I know, I have to use a second form for my popup since what I want to accomplish isn't as simple as something I could put in a MessageBox -- if there is another option, I'm all ears.
What I've been trying:
Form 1:
public partial class Form1 : Form
{
public void ChangeLabel()
{
label1.Text = StaticVariables.labelString;
}
}
Form 2:
public partial class Form2 : Form
{
private void changeForm1_Click(object sender, EventArgs e)
{
StaticVariables.labelString = textBox.Text;
Form1 frm = new Form1();
frm.ChangeLabel();
}
}
Obviously, that hasn't worked.
There's no need for the second form to know about the first form at all. Having it know about it complicates its code, and needlessly ties it to that form. Having another form knowing about the internal UI components of the main form is even worse; if you do that then changes to how the main form displays the data would break this other form. Just have the popup have a property representing the value that lets it be set/fetched externally:
public partial class Form2 : Form
{
public string Result //TODO give better name
{
get { return textBox.Text; }
}
public string DisplayText //TODO give better name
{
get { return label.Text; }
set { label.Text = value; }
}
}
Then the main form can set the display value, show the form, and fetch the resulting value:
Form2 popup = new Form2();
popup.DisplayText = "asdf";
popup.ShowDialog();
myField = popup.Result;
You need to create a new constructor that receives an instance of Form1 and store that as a field in Form2. Then, when you want to change the label use the instance that was passed in. I'm answering from my phone so when I get to my desk I can elaborate with code.
But what's happening here is that you're creating a new Form1 and setting the value.
private Form1 _form1;
...
public Form2(Form1 form1)
{
_form1 = form1;
}
...
private void changeForm1_Click(object sender, EventArgs e)
{
StaticVariables.labelString = textBox.Text;
_form1.ChangeLabel();
}
and then finally, when you launch Form2:
var form2 = new Form2(this);
form2.Show();
Related
I have 2 forms each with buttons, textboxes, and labels. In form1 I have a this code in a button event handler:
frmTwo form = new frmTwo ();
form.Show();
this.Visible = false; //closing form 1 when frmTwo opens
I went to the designer file for frmTwo and changed all of the controls: labels, textboxes, buttons from private (which was auto generated) to public.
Under this line of code: this.Visible = false; I want to put an if statement to check if a name textbox in frmTwo is blank. But when I write txtName.Text it says the textbox doesn't exist in the current context. I understand why it doesn't exist because its inside frmTwo NOT from1. But I'm not sure what other ways I can access this textbox because I already made it public in the designer. Is there another way to do this?
Ask yourself: Is it important for form1 that the information that you want to read from form2 is in a textbox? Would form1 really care if the same information would be kept by form2 in a ComboBox?
Wouldn't it be best if form1 doesn't know how form2 gets the information? All it has to know is that form2 is willing to provide the information. If form2 needs to read it from a database, or fetch it from the internet to fetch the information, why would form1 care? All form1 wants to know: "Hey Form2, give me information X"
Alas you didn't tell us if you want this information only once, or that form1 needs to be kept informed whenever information X changes. Let's assume that you do.
So, class Form2 will have a method to provide information X, and it is willing to tell everyone that information X is changed. Form2 does not show to the outside world how it gets its information. The current version holds information X in the text of TextBox1. Future versions might read it from a ComboBox, or read if from a file, or from the internet.
class Form2 : System.Windows.Window
{
public event EventHandler XChanged;
public string X
{
// information X is in textBox1
get => this.textBox1.Text;
}
private void TextBox1_Changed(object sender, ...)
{
// the text in textBox1 changed, so information X changed
this.OnXChanged();
}
protected virtual void OnXChanged()
{
this.XChanged?.Invoke(new Eventhandler(this, EventArgs.Empty));
}
... // other Form2 methods
}
Now if Form1 wants to know the value of X, it can simply ask for it:
Form2 form2 = ...
string informationX = form2.X;
If Form1 wants to be kept informed whenever information X changes:
form2.XChanged += InformationXChanged;
private void InformationXChanged(object sender, Eventargs e)
{
Form2 form2 = (Form2)sender;
// get the new information X from form2:
string informationX = form2.X;
this.ProcessInformationX(informationX);
}
If you want one form to replace the other, then you pass a reference to Form1 in the .Show() of Form2 and the form stores it in the .Owner property. The when the second form starts it will hide the first form. Additionally, when the second form closes it can unhide the first form.
Please use Capitalized names for types like Form and pascalCase for variables like mainForm = new Form().
Form1.cs
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var f2 = new Form2();
f2.Show(this);
}
}
Form2.cs
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.FormClosing += Form2_FormClosing;
this.Owner.Visible = false;
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
Owner.Visible = true;
}
public bool IsNameBlank { get => string.IsNullOrWhiteSpace(textBox1.Text); }
}
This is the basic framework. I also added some logic where Form1 checks for a textBox in Form2. Add a property in Form2 that returns the check:
and access it form From1
private void button1_Click(object sender, EventArgs e)
{
var f2 = new Form2();
f2.Show(this);
if (f2.IsNameBlank)
{
// textBox is empty.
}
}
I have two forms. First, Form1 has a group box, some labels and a listbox. I press a button and new Form2 is opened and contains some text. I want to transfer the text in Form2 to the listbox in the Form1.
So far, what I have done is make modifier of listbox to public and then put this code in the button of Form2
Form1 frm = new Form1();
frm.ListBox.items.Add(textBox.Text);
But amazingly, this does not add any value. I thought I was mistaken with the insertion so I made the same procedure. This time, I made a label public and added textbox value to its Text property but it failed.
Any ideas?
Try adding a parameter to the constructor of the second form (in your example, Form1) and passing the value that way. Once InitializeComponent() is called you can then add the parameter to the listbox as a choice.
public Form1(String customItem)
{
InitializeComponent();
this.myListBox.Items.Add(customItem);
}
// In the original form's code:
Form1 frm = new Form1(this.textBox.Text);
Let's assume Form1 calls Form2. Please look at the code:
Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
frm.Show();
frm.VisibleChanged += formVisibleChanged;
}
private void formVisibleChanged(object sender, EventArgs e)
{
Form2 frm = (Form2)sender;
if (!frm.Visible)
{
this.listBox1.Items.Add(frm.ReturnText);
frm.Dispose();
}
}
}
Form2:
public partial class Form2 : Form
{
public string ReturnText { get; set; }
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.ReturnText = this.textBox1.Text;
this.Visible = false;
}
}
The answer is to declare public property on Form2 and when form gets hidden. Access the same instance and retrieve the value.
Below code working perfect on my machine.
private void button1_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
f1.listBox1.Items.Add(textBox1.Text );//ListBox1 : Modifier property made public
f1.ShowDialog();
}
Ok, If you are Calling Sequence is like, Form1->Form2 and Form2 updates the value of Form1 then you have to use ParentForm() or Delegate to update the previous form.
Form1 frm = new Form1();
frm is now a new instance of class Form1.
frm does not refer to the original instance of Form1 that was displayed to the user.
One solution is, when creating the instance of Form2, pass it a reference to your current instance of Form1.
Please avoid the concept of making any public members like you said
>>i have done is make modifier of listbox to public and then in form2 in button code<<
this is not a good practice,on the other hand the good one is in Brad Christie's Post,I hope you got it.
This code will be inside the form containing myListBox probably inside a button click handler.
Form2 frm2 = new Form2();
frm2.ShowDialog();
this.myListBox.Items.Add(frm2.myTextBox.Text);
frm2.Dispose();
I am trying to disable some of the combo boxes in form 2 based in form 1 selected value.
Lets say
In Form1 if comboxbox value is 0
Disable certain combo boxes in form 2
What I have done in form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public ComboBox combo
{
get { return dropdown; }
}
and in form 2 so far
private void Form2_Load(object sender, EventArgs e)
{
Form1 f = new Form1();
if (f.combo.SelectedIndex == 0)
{
comboBox1.Enabled = false;
}
This is not working and I cant sort it out (new to c#)
If you create Form1 at Form with this syntax:
Form1 f = new Form1();
You will get new instance of Form1 (or "copy"), not the one thats already open. You need to pass the reference of Form1 to Form2.
Put this code into Form2:
private Form1 myParentForm;
public Form2(Form1 parentForm)
{
myParentForm = parentForm;
}
Then you can use Form1 through a variable myParentForm. Like this:
private void Form2_Load(object sender, EventArgs e)
{
if (myParentForm.combo.SelectedIndex == 0)
{
comboBox1.Enabled = false;
}
}
In Form1 you have a code something like this:
Form2 mySecondForm = new Form2();
change that to:
Form2 mySecondForm = new Form2(this);
Here is a prior answer with multiple samples calling one form as parameter to another including one of those as a full step-by-step sample.
Now, with respect to enable/disable, you can use either property or method approach to tell the "Other" form to enable / disable the status... The samples are just setting / getting values. If you do a set such as boolean to the one form in question, your setter portion might be something like
private bool enableFromOtherForm;
public bool EnableFromOtherForm
{
get { return enableFromOtherForm; }
set { this.controlToChange.IsEnabled = value; }
}
I am passing data between 2 windows forms in c#. Form1 is the main form, whose textbox will receive the text passed to it from form2_textbox & display it in its textbox (form1_textbox).
First, form1 opens, with an empty textbox and a button, on clicking on the form1_button, form2 opens.
In Form2, I entered a text in form2_textbox & then clicked the button (form2_button).ON click event of this button, it will send the text to form1's textbox & form1 will come in focus with its empty form1_textbox with a text received from form2.
I am using properties to implement this task.
FORM2.CS
public partial class Form2 : Form
{
//declare event in form 2
public event EventHandler SomeTextInSomeFormChanged;
public Form2()
{
InitializeComponent();
}
public string get_text_for_Form1
{
get { return form2_textBox1.Text; }
}
//On the button click event of form2, the text from form2 will be send to form1:
public void button1_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
f1.set_text_in_Form1 = get_text_for_Form1;
//if subscribers exists
if(SomeTextInSomeFormChanged != null)
{
SomeTextInSomeFormChanged(this, null);
}
}
}
FORM1.CS
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public string set_text_in_Form1
{
set { form1_textBox1.Text = value; }
}
private void form1_button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.Show();
f2.SomeTextInSomeFormChanged +=new EventHandler(f2_SomeTextInSomeFormChanged);
}
//in form 1 subcribe to event
Form2 form2 = new Form2();
public void f2_SomeTextInSomeFormChanged(object sender, EventArgs e)
{
this.Focus();
}
}
Now, in this case I have to again SHOW the form1 in order to automatically get the text in its textbox from form2, but I want that as I click the button on form2, the text is sent from Form2 to Form1, & the form1 comes in focus, with its textbox containing the text received from Form2.
I know this is a (really) old question, but hell..
The "best" solution for this is to have a "data" class that will handle holding whatever you need to pass across:
class Session
{
public Session()
{
//Init Vars here
}
public string foo {get; set;}
}
Then have a background "controller" class that can handle calling, showing/hiding forms (etc..)
class Controller
{
private Session m_Session;
public Controller(Session session, Form firstform)
{
m_Session = session;
ShowForm(firstform);
}
private ShowForm(Form firstform)
{
/*Yes, I'm implying that you also keep a reference to "Session"
* within each form, on construction.*/
Form currentform = firstform(m_Session);
DialogResult currentresult = currentform.ShowDialog();
//....
//Logic+Loops that handle calling forms and their behaviours..
}
}
And obviously, in your form, you can have a very simple click listener that's like..
//...
m_Session.foo = textbox.Text;
this.DialogResult = DialogResult.OK;
this.Close();
//...
Then, when you have your magical amazing forms, they can pass things between each other using the session object. If you want to have concurrent access, you might want to set up a mutex or semaphore depending on your needs (which you can also store a reference to within Session). There's also no reason why you cannot have similar controller logic within a parent dialog to control its children (and don't forget, DialogResult is great for simple forms)
This question already has answers here:
How to update textbox in form1 from form2?
(3 answers)
Closed 8 years ago.
I have Form1 that has a textbox and a button. When user clicks the button in Form1, Form2 opens up with a label control that carries the value of textbox in Form1.
What i did is set the textbox modifier of Form1 to Public, but when I call the textbox name of Form1 in Form2, I get an error that says
The name "txtbx1" doesn't exist in the current context
I wonder why since I already set the modifier of txtbx1 to Public.
Quick Note: i tried to instantiate Form1 in Form2 as:
Form1 f1 = new Form1();
and then call
f1.txtbx1.text
The odd thing is Form1 could not be instantiated (not highlighting occurs). On the other hand if i do Form2 f2 = new Form2(); Form2 gets highlighted!
This is how i show Form2 from Form1:
SetSalary salForm = new SetSalary();
salForm.ShowDialog();
Note that SetSalary represents Form2.
Any help will be appreciated.
make a constructor for form2 that accept string and in calling new form2 pass form1.frm1Textbox.text to contructor then set it to form2.frm2Textbox.text
Form2 form = new Form2(frm1Textbox.text);
in form2 constructor
public class Form2 : Form
{
public Form2(string text)
{
frm2Textbox.Text = text;
}
}
public partial class Form1 : Form
{
Form2 f = new Form2();
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = f.ans(); /*-- calling function ans() and textBox1.Text is inside form1--*/
}
}
create a public function ans() in form2....
public partial class Form2 : Form
{
public string ans()
{
string s = textBox1.Text;/*-- assigning value of texBox1.Text to local variable s and textBox1.Text is another text box which is inside form 2 --*/
return s; // returning s
}
}
To instantiate Form1 from Form2, class Form1 must be declared as public class Form1, or at least internal class Form1 if they are in the same assembly (project).
f1.txtbx1.text won't work because c# is case-sensitive and the property is called Text, not text.
Alternatively, you can declare a constructor with a parameter in Form2, so that you don't have to expose the TextBox member as public:
public class Form2 : Form
{
public Form2(string text)
{
txtbx1.Text = text; //txtbx1 does not need to be public
}
}
Then in Form1 you call var f2 = new Form2("label text goes here");
Expose a public property (or set of properties, if you have more than one value to pass in) on Form2 which will then fill the textbox. This hides the implementation detail of how it is displayed, if at all, and it also follows the standard used by built-in form classes. Example:
public class SetSalary {
public SetSalary() { }
public string SalaryText {
get { return txtbox1.Text; }
set { txtbox1.Text = value; }
}
}
Then, when launching SetSalary, you do this:
SetSalary form = new SetSalary();
form.SalaryText = srcTextBox.Text;
form.ShowDialog();
Good approach is to use Model-View-Presenter pattern. If you are a beginner (I think You are) then You should learn the basics by-the-book. This can help You minimize bugs and bad engineering, and will also maximize Your skill.
On Form1
public class Form1 : Form
{
public Form2()
{
InitializeComponent();
}
public static string MyTextBoxValue;
protected void button1_Click(object sender, EventArgs e)
{ MyTextBoxValue = TextBox1.Text;
}
}
On Form2
public class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
label1.Text=Form1.MyTextBoxValue;
}
}