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);
}
}
Related
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();
So I have 2 Forms:
Form1
Form2
There is a button on Form2, that I'd like to have hide Form1 when clicked.
Button Click from Button in Form2
var mainFrm = new Form1();
mainFrm.Hide();
This does nothing. I'm obviously missing something, but can't seem to figure it out.
Any help is definitely appreciated!
If your form1 is already present in the page, then why do you need to initialize it again? Just set the visible status to false to hide it.
mainFrm.Visible = false;
without seeing more of the code it's hard to answer, but you definitely need to reference the the old Form1 that is already visible and hide it. You are creating a new form and hiding it.
You have to define your Form2 class to store the reference to the main form.
public partial class Form2 : Form
{
/* reference to the main form will be stored here */
private Form1 _mainForm;
public Form2(Form1 mainForm)
{
InitializeComponent();
/* Initialize the main form field */
this._mainForm = mainForm;
}
private void button1_Click(object sender, EventArgs e)
{
/* Set the main form visibility to false */
_mainForm.Visible = false;
}
}
Now when you are creating the Form2 instance just add the main form to the constructor:
/* Show the form2 */
_form2 = new Form2(this);
_form2.Show();
Note: this will refer to the form that creates the Form2 object.
You could create a static form type property in your Form1 and set it when Form1 is Shown, and then use it to hide your form
Here is a code that worked for me.
private void button1_Click(object sender, EventArgs e)
{
var objForm1 = new Form1();
Form1.Fom1ref = objForm1;
objForm1.Show();
}
private void button2_Click(object sender, EventArgs e)
{
Form1.Fom1ref.Hide();
}
Here is the property that should be set in Form1.
public static Form Fom1ref { get; set; }
I have 2 forms which consist of:
Form1:
2buttons named:
btnCopy and
btnPaste
(with functions inside like rtb.Copy(); and rtb.Paste(); that should work for richtextbox in Form2)
Form2:
1richtextbox named: rtb
My question was:
How can I communicate between the 2buttons from Form1 (with its functions) and the richtextbox in Form2.
like: When I type text inside richtextbox(rtb) in Form2 then i SelectAll text then I Press the CopyButton(btnCopy) from Form1, text should be copied same as when I Press PasteButton(btnPaste) from Form1, text that has been copied should be Paste in RichTextBox(rtb) that could be Found on Form2 .
How can I do that?
Let's say you have Form1 and ToolStrip Button name PasteToolStripButton like:
public partial class Form1 : Form
{
Form2 formChild;
public Form1()
{
InitializeComponent();
this.Load += new EventHandler(Form1_Load);
}
void Form1_Load(object sender, EventArgs e)
{
formChild = new Form2();
formChild.MdiParent = this;
formChild.Show();
}
private void CopyToolStripButton_Click(object sender, EventArgs e)
{
formChild.CopyText(); // Method to copy Rich Text Box in Form2
}
private void PasteToolStripButton_Click(object sender, EventArgs e)
{
formChild.PasteText(); // Method in Form2 to Paste to the RichTextBox in Form2
}
}
In your Form2 you need to add a Public method named PasteText and CopyText like:
public void PasteText()
{
rtbChild.Text = Clipboard.GetText(); // this one simulates the rtb.Paste()
}
public void CopyText()
{
rtb.Copy();
}
I also named the RichTextBox in Form2 as rtbChild so every time you click for example paste in will be copied in your RichTextBox in Form2.
Create a public property on Form1 then set it from Form2.
EDIT:
On Form1:
public string TextForRTB {get; set;}
On Form2:
Form1 a = new Form1();
a.TextForRtb = rtb.Text;
Sol1: Pass one of the forms to the other, as Form1(Form parent){....} in the constructor, then you should see it's public properties and methods.
Sol2: Create custom events to raise it when text changed on your rich text box, so than the forms that initialized the form with this rich box will do something, like enable/disable a button or something
...Actually, there is a lot of solutions to this kind of behavior, and I wonder why you need to put your text box in a different form from your buttons that seems to be related very closely in business logic together!
You could expose 2 methods GetRichTextBoxContent and SetRichTextBoxContent in Form2.
Which would update the contents of richTextBox in Form2.
Then you could work on the Instance of Form2 form Form1
Note: The major think here is how you get the Instance of Form2. It is up to your implementation to get that instance.
public class Form2 : Form
{
public string GetRichTextBoxContent()
{
return this.richTextBox1.Text;
}
public void SetRichTextBoxContent(string content)
{
this.richTextBox1.Text = content;
}
}
public class Form1 : Form
{
//Based on your implementation
Form2 form2 = new Form2();
private void Button_CopyClick(object sender, EventArgs e)
{
var contentFromRtb = form2.GetRichTextBoxContent();
}
private void Button_PasteClick(object sender, EventArgs e)
{
var someContent = "Content to be copied to text box"
form2.SetRichTextBoxContent(someContent );
}
}
I have two Form classes, one of which has a ListBox. I need a setter for the SelectedIndex property of the ListBox, which I want to call from the second Form.
At the moment I am doing the following:
Form 1
public int MyListBoxSelectedIndex
{
set { lsbMyList.SelectedIndex = value; }
}
Form 2
private ControlForm mainForm; // form 1
public AddNewObjForm()
{
InitializeComponent();
mainForm = new ControlForm();
}
public void SomeMethod()
{
mainForm.MyListBoxSelectedIndex = -1;
}
Is this the best way to do this?
Making them Singleton is not a completely bad idea, but personally I would not prefer to do it that way. I'd rather pass the reference of one to another form. Here's an example.
Form1 triggers Form2 to open. Form2 has overloaded constructor which takes calling form as argument and provides its reference to Form2 members. This solves the communication problem. For example I've exposed Label Property as public in Form1 which is modified in Form2.
With this approach you can do communication in different ways.
Download Link for Sample Project
//Your Form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2(this);
frm.Show();
}
public string LabelText
{
get { return Lbl.Text; }
set { Lbl.Text = value; }
}
}
//Your Form2
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private Form1 mainForm = null;
public Form2(Form callingForm)
{
mainForm = callingForm as Form1;
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
this.mainForm.LabelText = txtMessage.Text;
}
}
(source: ruchitsurati.net)
(source: ruchitsurati.net)
Access the form's controls like this:
formname.controls[Index]
You can cast as appropriate control type, Example:
DataGridView dgv = (DataGridView) formname.Controls[Index];
I usually use the Singleton Design Pattern for something like this http://en.wikipedia.org/wiki/Singleton_pattern . I'll make the main form that the application is running under the singleton, and then create accessors to forms and controls I want to touch in other areas. The other forms can then either get a pointer to the control they want to modify, or the data in the main part of the application they wish to change.
Another approach is to setup events on the different forms for communicating, and use the main form as a hub of sorts to pass the event messages from one form to another within the application.
It's easy, first you can access the other form like this:
(let's say your other form is Form2)
//in Form 1
Form2 F2 = new Form2();
foreach (Control c in F2.Controls)
if(c.Name == "TextBox1")
c.Text = "hello from Form1";
That's it, you just write in TextBox1 in Form2 from Form1.
If ChildForm wants to access the ParentForm
Pass ParentForm instance to the ChildForm constructor.
public partial class ParentForm: Form
{
public ParentForm()
{
InitializeComponent();
}
public string ParentProperty{get;set;}
private void CreateChild()
{
var childForm = new ChildForm(this);
childForm.Show();
}
}
public partial class ChildForm : Form
{
private ParentForm parentForm;
public ChildForm(ParentForm parent)
{
InitializeComponent();
parentForm = parent;
parentForm.ParentProperty = "Value from Child";
}
}
There is one more way, in case you don't want to loop through "ALL" controls like Joe Dabones suggested.
Make a function in Form2 and call it from Form1.
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public void SetIndex(int value)
{
lsbMyList.SelectedIndex = value;
}
}
public partial class Form1 : Form
{
public Form2 frm;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
frm=new Form2();
frm.Show();
}
private void button1_Click(object sender, EventArgs e)
{
frm.SetIndex(Int.Parse(textBox1.Text));
}
}
Here's also another example that does "Find and Highlight". There's a second form (a modal) that opens and contains a textbox to enter some text and then our program finds and highlights the searched text in the RichTextBox (in the calling form). In order to select the RichTextBox element in the calling form, we can use the .Controls.OfType<T>() method:
private void findHltBtn_Click(object sender, EventArgs e)
{
var StrBox = _callingForm.Controls.OfType<RichTextBox>().First(ctrl => ctrl.Name == "richTextBox1");
StrBox.SelectionBackColor = Color.White;
var SearchStr = findTxtBox.Text;
int SearchStrLoc = StrBox.Find(SearchStr);
StrBox.Select(SearchStrLoc, SearchStr.Length);
StrBox.SelectionBackColor = Color.Yellow;
}
Also in the same class (modal's form), to access the calling form use the technique mentioned in the #CuiousGeek's answer:
public partial class FindHltModalForm : Form
{
private Form2 _callingForm = null;
public FindHltModalForm()
{
InitializeComponent();
}
public FindHltModalForm(Form2 CallingForm)
{
_callingForm = CallingForm;
InitializeComponent();
}
//...
So I want basically the user to login in first in order to use the other form. However, my dilemma is that the login box is in Form2, and the main form is Form1.
if ((struseremail.Equals(username)) && (strpasswd.Equals(password)))
{
MessageBox.Show("Logged in");
form1.Visible = true;
form1.WindowState = FormWindowState.Maximized;
}
else
{
MessageBox.Show("Wow, how did you screw this one up?");
}
However, Form1 doesn't become visible, (since I launch it as visble = false) after they log in. Can someone help?
EDIT:
Brilliant response, but my problem is still here. I basically want to load Form2 First, (which is easy I run Form1 and set it to hide) But when Form2 is closed, I want Form1 to be closed as well.
private void Form2_FormClosing(Object sender, FormClosingEventArgs e)
{
Form1 form1 = new Form1();
form1.Close();
MessageBox.Show("Closing");
}
this doesn't seem to work...
You will need to pass the reference of one form to another, so that it can be used in the other form. Here I've given an example of how two different forms can communicate with each other. This example modifies the text of a Label in one form from another form.
Download Link for Sample Project
//Your Form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2(this);
frm.Show();
}
public string LabelText
{
get { return Lbl.Text; }
set { Lbl.Text = value; }
}
}
//Your Form2
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private Form1 mainForm = null;
public Form2(Form callingForm)
{
mainForm = callingForm as Form1;
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
this.mainForm.LabelText = txtMessage.Text;
}
//Added later, closing Form1 when Form2 is closed.
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
mainForm.Close();
}
}
(source: ruchitsurati.net)
(source: ruchitsurati.net)
When you log in and do Form1.visible = true; have you also tried Form1.Show(); that should show form2
However, Personally, I would prefer setting the application to run form2 directly in the program.cs file.
static void Main()
{
Application.Run(new Form2());
}
then when user successfully logs in, do
form1.Show();
this.Hide(); // this part is up to you
mind you, in form2, when / after you instantiate form1, you might want to also add this :
newform1.FormClosed += delegate(System.Object o, FormClosedEventArgs earg)
{ this.Close(); };
this closes form2 when form1 is closed
better yet do form1.Show() in a new thread, and then this.Close(); for form2. this removes the need of adding to the form2's FormClosed event: you can thus close form2 immediately after starting form1 in a new thread. But working with threads might get a little complicated.
EDIT:
form2 is form1's parent. if form2 is your main application form, closing it closes your program (generally). Thus you either want to just hide and disable form2, and close it only after form1 is closed, or start form1 in a new thread. Your edit pretty much opens form1, then immediately closes it.