Can't update value on the main form - c#

I my game on the WF I have a main form (left) and it's child form (right). In the child form I can change value of the progress bar and it works fine. But I have the same progress bar on the main form and I want to update it too. I can't do it.
VIDEO
Code of the child form:
private MainForm mainForm = new MainForm();
// Button "Close"
private void button2_Click(object sender, EventArgs e)
{
mainForm.MyInitializeComponent(); // This code must update value on the main form
this.Close();
}
Code of the main form:
public void MyInitializeComponent()
{
label33.Text = indicators.Food + "%";
progressBar1.Value = indicators.Food;
}
If I'll open child form after I closed it, I see the changed value, ie it is stored. In both forms, the value is taken from a single variable.
Indicators.cs:
public sealed class Indicators
{
public Indicators()
{
Indicators.food = 75;
}
private static int food;
public int Food
{
get { return food; }
set { food = value; }
}
}

Have the main form add a form closed handler to the child form to update it's UI when the child is closed:
var childForm = new ChildForm();
childForm.FormClosed += (s, args) => MyInitializeComponent();
//...
childForm.Show();

Related

How to get the current position of the dialog in win forms?

I have a dialog that I can drag it around the screen.When I close the dialog and open again. I want it to be shown in the last position it was before.
How can I save the last position of the dialog in win forms?
Sample & dirty solution.
In solution we have two forms. Form1, Form2, and Settings static class.
public static class Settings
{
public static int X = 0;
public static int Y = 0;
}
Inside Form1 we have button1 that will be responsible to show Form2.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
frm.StartPosition = FormStartPosition.Manual;
frm.Location = new Point(Settings.X, Settings.Y);
frm.ShowDialog();
}
}
Inside Form2 we have ClosingEvent Handler :
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
Settings.X = this.Location.X;
Settings.Y = this.Location.Y;
}
}
When Form2 is closing we are storing location to static Settings class. Later we are reading from this class X and Y position.
I hope it was helpful.
You need to:
1) create your custom "dialog", which is basically Windows.Forms.Form.
FormStartPosition property set to Manual.
2) once created, in its OnClosing event save its position somewhere from Location property
3) next time you are going to show it, assign the value you've saved before.

Update textbox contained within a different form

I have 2 forms. The second form is opened from a method in the first form and I wish to be able to update the textbox that exists within that second form.
Basically I have the following code:
private void sendAllButton_Click(object sender, EventArgs e)
{
SendConsoleGUI sendOutGUI = new SendConsoleGUI();
sendOutGUI.Show();
sendOutGUI.sendConsoleTextBox.Text = "Test";
}
When I press the button the second form (SendConsoleGUI form) opens but "Test" is never added to its textbox.
Am I doing something wrong here?
You need to use invoke method.
sendOutGUI.Invoke((MethodInvoker) delegate { sendOutGUI.sendConsoleTextBox.Text = "Test"; });
public partial class ParentForm : Form
{
public ParentForm()
{
InitializeComponent();
}
private void sendAllButton_Click(object sender, EventArgs e)
{
SendConsoleGUI sendOutGUI = new SendConsoleGUI("Test");
sendOutGUI.Show();
}
}
public partial class ChildForm : Form
{
public ChildForm(string str)
{
InitializeComponent();
sendConsoleTextBox.Text = str;
}
}
This will work for you if you only wish to update it when the ChildForm is initially created.

How to call Parent Form method from Child Form in C#?

I have a parent form with 1 method to refresh the panel content called resetPanel() .
I also have a button in the parent form. If I click the button, a new form opens up. I will do some changes and click on save. The content gets saved in the database and the child form closes. Now the parent form will be displayed.
I want to call the resetPanel() method now, so that the panel shows the updated values.
How can I achieve this?
If your child form is a dialog one, you can just check the form's dialog result:
// Do not forget to release resources acquired:
// wrap IDisposable into using(..) {...}
using (Form myChildForm = new MyChildForm()) {
//TODO: If you want to pass something from the main form to child one: do it
// On any result save "Cancel" update the panel
if (myChildForm.ShowDialog() != DialogResult.Cancel)
resetPanel();
}
In case your child from is not a dialog you can pass this into child form as reference to main one:
Form myChildForm = new MyChildForm(this);
myChildForm.Show(); // <- Just show, not ShowDialog()
...
private MyMainForm m_MainForm;
public MyChildForm(MyMainForm form) {
m_MainForm = form;
}
private void save() {
//TODO: Save to database here
// Main form update
if (!Object.ReferenceEquals(null, m_MainForm))
m_MainForm.resetPanel(); // <- resetPanel should be public or internal method
}
private saveButton_Click(object sender, EventArgs e) {
save();
}
After you close your Form2, you can call the ResetPanel method:
Form2 f2 = new Form2();
f2.ShowDialog();
resetPanel(); // <-- this will be executed when you close the second form
for Eg ur Parent Form Name If form Form1 and child Form Name as Form2 goto ur Child form Designer page Change it Access Modifier as Public
and from what ever method you want Call
Form2 f2=new Form2();
f2.Show();
.//from here on you can write your concerned code
If your resetPanel method is doing a database call, you quite possibly can avoid it. Although this will not get any data that was being updated by another user in your application. Just modified code from another answer of mine for your needs. This is just a sample:
public class ParentForm : Form
{
Button openButton = new Button();
public ParentForm()
{
openButton.Click += openButton_Click;
}
void openButton_Click(object sender, EventArgs e)
{
ChildForm childForm = new ChildForm();
childForm.OKButtonClick += childForm_OKButtonClick;
childForm.ShowDialog();
}
void childForm_OKButtonClick(object sender, MyEventArgs e)
{
// Use properties from event args and set data in this form
}
}
public class ChildForm : Form
{
Button okButton = new Button();
TextBox name = new TextBox();
TextBox address = new TextBox();
public event EventHandler<MyEventArgs> OKButtonClick;
public ChildForm()
{
okButton.Click += okButton_Click;
}
void okButton_Click(object sender, EventArgs e)
{
try
{
bool saveSucceeded = false;
// Try saving data here
if (saveSucceeded)
{
if (OKButtonClick != null)
{
MyEventArgs myEventArgs = new MyEventArgs();
// Just get updated data from screen and send it to another form
myEventArgs.Name = name.Text;
myEventArgs.Address = address.Text;
OKButtonClick(sender, myEventArgs);
}
Close();
}
else
{
MessageBox.Show("Data could not be saved.");
}
}
catch (Exception ex)
{
// Perform proper exception handling
}
}
}
public class MyEventArgs : EventArgs
{
public string Name
{
get;
set;
}
public string Address
{
get;
set;
}
}
Try to set the Save button in your child Form to DialogResult.Ok and then make the Save button as the AcceptButton for child Form. And then test if the result if it the user press that Save Button. Programmatically it could look like this:
Form2 chidForm = new Form2();
childForm.btnSave.DialogResult = DialogResult.Ok
childForm.AcceptButton = childForm.btnSave
if (childForm.ShowDialog() == DialogResult.Ok)
{
resetPanel();
}
Now, I assume here that your Save button in Child Form is named btnSave.

C# Windows Forms - link instances of same Form

I'd like to create, say 32 Windows Forms based upon a single template Form, and those instances should be linked to each other. That is, every Form has a button for calling the next instance and so on. I am able to create as many forms as I like but how would I link those instances together ?
This is what I use to create several child forms:
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ChildForm child = new ChildForm();
child.Show();
}
}
Sequence of events would be like:
User starts application, main form is displayed (only has "Open Child" button)
User pushes "Open child" button, first instance of child form opens
first child form (caption "Child Form 1") has button "Open Child Form 2"
if user pushes "Open Child Form 2" child form 1 is hidden and child form 2 is displayed
if the last child form is reached wrap-around to child form 1
Any ideas are welcome !
regards
Chris
You can create a static collection of the form, in the constructor add the form instance to the list (and remove it during dispose). To figure out the next form, you can find the index of the current form and grab the next form in the list based on that. Create a form with two buttons and modify it as below to test it out.
public partial class Form1 : Form
{
static List<Form1> formList = new List<Form1>();
public Form1()
{
InitializeComponent();
formList.Add(this);
}
private void button1_Click(object sender, EventArgs e)
{
int idx = formList.IndexOf(this);
int nextIdx = (idx == formList.Count()-1 ? 0: idx+1 );
Form1 nextForm = formList[nextIdx];
nextForm.changeTextAndFocus("next form: " + nextIdx);
}
// moves to the next form and changes the text
public void changeTextAndFocus(string txt)
{
this.Focus();
this.Text = txt;
}
//Creates 5 forms
private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < 5; i++)
{
Form1 newForm = new Form1();
newForm.Show();
}
}
}
I don't really know what you are planning to do :). If you want to count several forms, you can add a property Number to the form. And searching upwards from there.
Mainform;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ChildForm first = new ChildForm();
first.Number = 1;
first.Show();
}
}
ChildForm
public partial class ChildForm : Form
{
public ChildForm()
{
// createButton here
}
private void button_Click(object sender, EventArgs e)
{
ChildForm _childForm = new ChildForm();
_childForm.Owner = this;
_childForm.Number = this.Number + 1;
this.Hide();
_childForm.Show();
}
public void FirstChildForm()
{
if (this.Number != 1) //maybe not that static
{
(this.Owner as ChildForm).FirstChildForm();
this.Close(); // or hide or whatever
}
}
public int Number
{ get; set; }
}
Not tested code, hope this helps a bit :).

change label text of parent form from child form [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
accessing controls on parentform from childform
I have parent form form1 and child form test1 i want to change label text of parent form from child form in my parent form i have method to showresult()
public void ShowResult()
{ label1.Text="hello"; }
I want to change label.Text="Bye"; form my child form test1 on button click event. Please give any suggestions.
when calling the child form, set the Parent property of child form object like this..
Test1Form test1 = new Test1Form();
test1.Show(this);
On your parent form, make the property of your label text like as..
public string LabelText
{
get
{
return Label1.Text;
}
set
{
Label1.Text = value;
}
}
From your child form you can get the label text like that..
((Form1)this.Owner).LabelText = "Your Text";
No doubt there are plenty of short cut ways to do this, but in my view a good approach would be to raise an event from the child form that requests that the parent form changes the displayed text. The parent form should register for this event when the child is created and can then respond to it by actually setting the text.
So in code this would look something like this:
public delegate void RequestLabelTextChangeDelegate(string newText);
public partial class Form2 : Form
{
public event RequestLabelTextChangeDelegate RequestLabelTextChange;
private void button1_Click(object sender, EventArgs e)
{
if (RequestLabelTextChange != null)
{
RequestLabelTextChange("Bye");
}
}
public Form2()
{
InitializeComponent();
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.RequestLabelTextChange += f2_RequestLabelTextChange;
}
void f2_RequestLabelTextChange(string newText)
{
label1.Text = newText;
}
}
Its a bit more long winded but it de-couples your child form from having any knowledge of its parent. This is a good pattern for re-usability as it means the child form could be used again in another host (that doesn't have a label) without breaking.
Try something like this:
Test1Form test1 = new Test1Form();
test1.Show(form1);
((Form1)test1.Owner).label.Text = "Bye";

Categories

Resources