Okay, this is a simple question, but it's been racking my brain for a while now.
I have two forms: Form1and Form2.
I have some checkboxes on Form2, and I want to use data from checked check boxes on Form2 on Form1 but when I add the following code on Form1 it's giving me errors:
if (cbTESTING.Checked)
{
uri_testings += string.Format("{0}.TESTINGS,", word);
}
I'm getting an error with cbTESTING as it's not referenced on Form1.
How can I use or reference checkboxes from Form2 in Form1?
I would do something like this:
Since Form1 creates Form2, and Form1 needs to manipulate Form2 then you can change this from Form2.Designer.cs:
private System.Windows.Forms.Checkbox cbTESTING;
To:
public System.Windows.Forms.Checkbox cbTESTING;
Assuming in Form1 you created Form2 like this:
Form2 f2 = Form2();
f2.Show();
Then you use this to check cbTESTING:
if(f2.cbTESTING.Checked) // do stuff ;
EDIT: I have seen your comment which says they do not relate to each other at all which makes it impossible to achieve in any easy method. What you said implies communication between these two THREADS since each Form runs in a Thread and these threads are unrelated. Communication is NOT an easy thing to do, you can try it using UDP and Events but trust me, having a direct relation between them would make things MUCH easier for you.
Anyway, I would assume some other Form or Thread would launch these Forms?
I managed to do this by making the checkboxes save values in the properties settings default and then calling them that way as every time i wanted to open the program instead of having to click them again it's auto saved my current values.
Thank you all for your help though.
Here is some code for future reference if anyone else wanted to do it the way I did.
Here is the code that saves it to the settings.
if (cbTESTING.Checked)
Properties.Settings.Default.cbTESTING = true;
else
Properties.Settings.Default.cbTESTing = false;
and here was the code to call that in a different form.
if (Properties.Settings.Default.cbTESTING == true)
{
uri_domains += string.Format("{0}.testing,", word);
}
Hope this will help someone in the future!
Here's a pretty clean way to fix this.. just change the access modifier to public for cbTESTING in the designer for Form2.
That is, in Form2.Designer.cs, change
private System.Windows.Forms.Checkbox cbTESTING;
to
public System.Windows.Forms.Checkbox cbTESTING;
Then, Form1 can look like this:
public partial class Form1 : Form
{
public Form1() {
InitalizeComponent();
Form2 secondForm = new Form2();
bool isChecked = secondForm.cbTESTING.checked;
}
}
Edits: removed protected solution, which isn't a great option in this case.
Here you have a ugly way to do what you want:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var frm = new Form2();
frm.ShowDialog();
label1.Text = frm.TextBoxChecked;
}
}
//Just declare a prop into Form2 a set it with the value you need
public partial class Form2 : Form
{
public string TextBoxChecked { get; set; }
public Form2()
{
InitializeComponent();
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
TextBoxChecked = "Checkbox_1_checked";
else
TextBoxChecked = "Checkbox_1_unchecked";
}
}
Lets do things in a cool way.
Maybe a good aproache is to say to Form2: "Hey you, when your checkbox change let me know", It sounds like a callback. So let do it:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void doWhenCheckBoxChange(string text)
{
//I'm receiving the notification indicating that the checkbox has changed
label1.Text = text;
}
private void button1_Click(object sender, EventArgs e)
{
var frm = new Form2();
//I'm passing a callback to Form2, Here is where I say
//"Hey you, let me know where your checkbox change"
frm.DoWhenCheckboxChange = doWhenCheckBoxChange;
frm.ShowDialog();
//label1.Text = frm.TextBoxChecked;
}
}
public partial class Form2 : Form
{
//public string TextBoxChecked { get; set; }
public Action<string> DoWhenCheckboxChange;
public Form2()
{
InitializeComponent();
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
//TextBoxChecked = "Checkbox_1";
//Notify to Form1 that checkbox has changed.
if (checkBox1.Checked)
DoWhenCheckboxChange("Checkbox_1_checked");
else
DoWhenCheckboxChange("Checkbox_1_unchecked");
}
}
If you test the second aproache, you will discover that you dont need to close your Form2 to see the changes.
Might not be the most elegant solution but will definitely work. Declare a public static bool variable in Form2. Add Checkbox changed event to your checkboxes and change those static variables accordingly. Then just check those variable in Form1 such as Form2.VariableName let me know if you need further explanation
Edit
In Form2 declare public static bool CheckBoxStatus = false; false by default, you can change that.
Also in Form2 add following event checkBox1.CheckedChanged += new EventHandler(CheckedChanged) and add appropriate function such as
private void CheckedChanged(object sender, EventArgs e)
{
CheckBoxStatus = checkBox1.Checked;
}
And Finally in Form1 one you can simply check if that checkbox is checked like this
if(Form2.CheckBoxStatus == true) ;
else ;
Hope that helps.
*PS sorry my formatting, new to posting answers here.
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'm trying to use chart to show some graphics.
I have two Forms (Form1 and Form2 ).The chart is located in Form2, but I want to write the code in Form1, like let's say in Form1 when I click on GRAPHIC button will show me chart in Form2.
The problem is when I write the code in Form1, it give me error saying the name of the chart(which is found in Form2) not found in Form1. How can I solve this problem.
This is part of my code:
private void button2_Click(object sender, EventArgs e) // Graphic
{
Form2 fr2 = new Form2(A );
this.Hide();
fr2.ShowDialog();
chart1.series["student's grad"].Points.Addxy("A", A);
}
You can try this
public Form2(object A)
{
InitializeComponent();
chart1.series["student's grad"].Points.Addxy("A", A);
}
A couple things that I can see, the first is that you are using ShowDialog which will run fr2 as a Modal Dialog box which will Block Form1 until you close fr2, the second is that since you are wanting to access the Chart in frm2 you would either need to use a Public Property/Method or make your Chart's Visibility Public. I would recommend that you use a Property or a Public Method that way you are keeping the internals of your second Form Hidden.
Something like this might work for you:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 fr2 = new Form2();
this.Hide();
fr2.AddPoint("student's grad", new Point( 0,0));
fr2.ShowDialog();
}
}
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public void AddPoint( string series, Point chartPoint)
{
chart1.Series["student's grad"].Points.AddXY(chartPoint.X, chartPoint.Y);
}
}
I am trying to add a new item to a listbox in form1 from form2. The idea behind it is to end up with a list of different items each being different from each other (or the same, doesnt matter) based on the form2 activity. Say I open form1 (and it has shopping list (listbox))and I open form2 and click button which would add "bannana" to the list in form1. How do I do this? I've tryed various ways such as adding "addToList(parameter)" method in the form1 and then calling it from form2 and passing parameters but the list would remain empty however other things such as message box would pop up etc. So any ideas how to solve this?
I am using this method in form one to add the items into the list and it works:
public void addToList()
{
MessageBox.Show("Adding stuff to list");
listEvent.Items.Add("New item 1");
listEvent.Items.Add("new item 2");
MessageBox.Show("Done adding");
listEvent.Refresh();
}
Now when I try to call it from another class/form I use this:
public void changeForm()
{
EventPlanner mainEventForm = new EventPlanner();
mainEventForm.addToList();
}
Or:
private void btnAddEvent_Click(object sender, EventArgs e)
{
EventPlanner mainEventForm = new EventPlanner();
mainEventForm.addToList();
}
But it still doesnt work. Although when I use it from form1 (eventplanner, where the list is) it works perfectly fine. I even changed access modifyer to public so that shouldnt be the problem.
You can use a public Method on Form2 as I mentioned in my comment to your question. Here is a simple example.
Form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
if (frm2.ShowDialog(this) == DialogResult.OK)
{
listBox1.Items.Add(frm2.getItem());
}
frm2.Close();
frm2.Dispose();
}
}
From2
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
button1.DialogResult = DialogResult.OK;
button2.DialogResult = DialogResult.Cancel;
}
public string getItem()
{
return textBox1.Text;
}
}