How to call Form2 in Form1 - c#

I'm doing a shop with 7 forms, the form 1 is the basic of the store with picture's Box and a textbox saying how much should I pay. When I click in the picture's box, for example in a T-shirt, it opens a new Form with some information and a button saying "add to cart".
Basically I want to click on the button "add to cart" and then the Form2 closes and back's to form 1 and in the textbox (that shows how much should I pay) shows the value.

Forms are objects like any other, and you can pass references to them and call methods on them like any other.
For example, let's say you expose a method on Form1 which accepts the value and updates the UI:
public void UpdatePayAmount(double amount)
{
// use the supplied value to update your text box
}
Then you would want to call that method from Form2 when clicking on the "Add to Cart" button. Something like:
form1Instance.UpdatePayAmount(someAmountValue);
So your Form2 code needs a reference to an instance of Form1 in a variable somewhere. Since Form2 now depends on Form1, a sensible place to put that requirement would be in its constructor. Perhaps populating a private field:
private Form1 form1Instance;
public Form2(Form1 form1)
{
form1Instance = form1;
}
Now Form2 requires a reference to an instance of Form1 when you create it, so it can call a method on that instance when the button is clicked. So when you create Form2 in your Form1 code you would supply that instance:
form2 = new Form2(this);
form2.Show();

Related

Pass data from Form1 to class1 using delegate and event

I know how to pass data using event and delegate from Form2 to Form1 (backwards actually).
But I would like to know how to do it appropriately from Form1 (main form) to Form2.
Imagine Form2 and some center form to show some progress (with a progressbar) which would be common for plenty of other forms.
This is how I would like to look like:
public partial class Form2 : Form
{
public delegate void ProgressEvent(object obj);
public event ProgressEvent OnProgressShowing;
public Form2()
{
}
private void ShowingProgress(object obj)
{
//calling this method from Form1
//But it must be PRIVATE!
}
}
How to do it?
Like?
Form2 f2 = new Form2();
f2.OnProgressShowing += new Forms.ProgressEvent(?? ?what to put inside here?? I cannot access a private method on form2 ???);
I know one option is to create delegate and event on Form1, and pass a Form1`s reference to Form2, and subscribe to an event from Form2. But this is not what I would like. I would then have plenty of delegates and events in each of the other forms which would call this form2.
Since your first form is creating an instance of your second form and "owning" that instance, it is appropriate design for the method on Form2 that updates the UI based on the current progress to be public, and for the other forms calling it to call that method. There is also no need for Form2 to have an event at all, since it is not the one informing other forms that something has happened.
In this case, when creating a design document to indicate the relationships between these forms, we can say that Form1, or other forms have a Form2. A HAS-A relationship makes sense here. For Form2 it's goal is simply to display progress based on information provided by another class, so having a public method for another class to tell it to display progress is correct.
You're missing up a reversed relationship. If the child form needed to inform the parent forms of something, then Form2 would have an event, and in the handler of that event the forms creating it (i.e. Form1) would generally be calling their own private methods in the handler, or possibly accessing other public methods of Form2 to pull or push data out of it.
The idea here is that is'a appropriate for Form1 to "know about" Form2. It's appropriate for it to have a reference to it, and to know about whatever it exposes publicly. Form2, however, shouldn't know anything about what form creates it. It should be able to display progress for any form that can tell it what progress to show. If it needs to accept a reference to Form1 or know anything about it at all, then that can't happen. By using an event on Form2 when it needs to pass information out to the form that creates it, it can avoid needing to know what form that is.

Access a TextBox from another class in workspace

I want to use a textBox, which is on my main form Form1 from other class. In class Form1 I can use:
this.Invoke(new EventHandler(displayText));
and then
private void displayAccFields(object o, EventArgs e)
{
tbAccRoll.AppendText(packParameters.getPackage(3) + "");
}
and it works fine.
How can I access this textbox for displaying something from a different class?
For sending values between two forms, you may
Send the values in the constructor of the second form. You may create a paramterized constructor and send the values when you initialize the form.
You may take a reference in to your first form in the second form.
In second form,
public Form1 objForm1;
and in First Form,
Form2 objForm2=new Form2();
Form2.objForm1=this;
and then you can use Form2's objForm1 to refer to Form1's textbox.

How can I access the controls from another running window form in c#

Actually, I am a newbie for C#. In my program, I got two window forms.Each window forms have one label and one activate button.Once I start(load) the program,two window forms will pop-up together.My intention is when I click on the form1 activate button,my form1 label's back colour will change to "green"(to let user know this form1 is activated).Up to here I can write the soft code.But when I click on the form2 activate button,form1 will no longer active, my form2 will be activated and form2 label's back colour will also change to "green".Since form1 is no longer active,I would like to change my form1 label's back colour to red.How can I change it?
How I write my program so far.
In form1 activate button click
1.form1 label's back colour = Colour.green // to let user know form1 is activate upon button click
2. form2 f2 = new form2();
f2.(form2 label's).BackColour = Colour.red
There is no change on form2.
when I add f2.Show() , once I click the activate button on form1 , form2 will pop-up with red label back colour.
Please remember that I am running both form1 and form2 on my Mainform.
Thanks In Advance.
Your forms are just regular c# classes, and the form controls are private members of these classes.
If you need to have public access to few of those controls, just create a public property for those controls.
public Button MyColorButton
{
get { return MyButton; }
}

Value from Form2 not updating in Form2

I have 2 forms in C# desktop application. Form1 and Form2.
Form1 contains a public method that adds item in ListBox control as follows:
public void AddToList(string item)
{
listBox.Items.Add(item);
}
When I call this method directly on some button press then it works fine. But when I call this method from Form2, it doesn't add anything in ListBox control on Form1. Code in Form2 is as below:
Form1 frm = new Form1();
frm.AddToList("something");
When I run this nothing happens. No error nothing. It just doesn't add any item into ListBox.
What am I doing wrong?
You're creating a new instance of Form1 and adding an item to it's listbox, rather than getting an instance of the Form1 you no doubt already have and calling the method on that.
The naive approach is to have a parameter in the Form2 constructor that takes an instance of Form1 and saves it as an instance variable for use in this event handler.
I don't much like that approach from a design perspective.
I would suggest creating a public event in Form2, having Form1 subscribe to that event and add a handler that add the item to the listbox. The Event in Form2 would look something like this:
public event EventHandler ButtonClick
{
add
{
button1.Click += value;
}
remove
{
button1.Click += value;
}
}
Then you'll have a property that looks something like this:
public string SomeValueForm1NeedsOnButtonClick
{
get
{
return texbox1.Text;
}
}
Then in Form1 you'll have something like:
Form2 otherForm = new Form2();
otherForm.ButtonClick += (sender, args) =>
{
listbox1.Items.Add(otherForm.SomeValueForm1NeedsOnButtonClick);
};
This approach ensures that each form only knows as little as possible about each other form. It reduces Coupling between the two classes and makes it clearer to future users/readers of the forms exactly what communication takes place between them.
Form1 frm = new Form1();
this line is creating a brand new instance of Form2... not the same instance that is already displayed on the screen. so you are adding to the listbox of this secondary instance that is never shown on the screen.
Hmm
If you followed that code with frm.Show() you would have seen it. Isuspect that's not waht you want.
Your approach to the is problem is a tad naive.
You could add a property to form2 and set it to the Form1 instnace you want to use. (PS form1 and form2 are not helping, give them propernames. MainForm and DetailForm or somesuch).
The problem with the above is you've implemented a horrible dependancy.
Lots of ways to go with this, one would be a seperate class to hold the list (an interface and a class would be even better).
Then add a property to Form1 and Form2 of teh ihneterface or class type.
Form2 can then add things to the list.
That raises a list changed event.
Form1 hooks into with an event handler and then refreshes the listbox it's using to display the the doings.
Once you have the infrasturure in polace you can do all sorts of things with it, whereas the method you are using is a lot of code and messing about for very little reward.

Start new form on closing one. C#

When my program runs it closes form1 after a few seconds. Depending on what happened during form1's lifespan I may want to open form2. Normally I would just make a new instance of form2 and use the show() method. But form2 is then a child of form1 and then also closes. Does any body have an idea on how to get this to work? thanks.
For multi-form applications I tend to have one form that is the "main" form, which opens up the sub forms.
The main form is the one that gets started with Application.Run(...)
In your case you might want to have a blank form that can be the controller, and have Application.Run call that.
That form can then start instantiate your Form1 and run it.
e.g.
public ControlForm : public Form
{
Form1 form1;
Form2 form2;
public ControlForm()
{
form1 = new Form1();
form2 = new Form2();
}
public void Start() // or something similar
{
form1.ShowDialog(); // will block showing the form, or you can do other tricks
// to show the form here
if(form1.someFlag) form2.ShowDialog();
}
}
This is just "psudo-C#" code, but hopefully the concept makes sense
Then your main function can just run "ControlForm"
Its just a concept you might want to try
You can open a new form in your application's bootstrapper (main method). You will want to call Application.Run(yourFormHere). You would have two of these in a row in the order you want to show the forms. You could store the results of the first form in some static location and check that before showing the second form.
I ended up doing this:
Auth f = new Form1();
Application.Run(f);
if (f.authed)
{
Application.Run(new Form2());
}
I don't think that your problem is that the Form2 instance is a child form of the Form1 instance, but rather that the Form1 instance is your applications main form. That will make your application quit whenever Form1 closed. One way to prevent this is to alter the main method to not set Form1 as the main form (see here for details on that).

Categories