So i have 2 forms.
Form 1 is my main form, and form 2 is where I enter text in a textbox to be displayed on a label on form 1. Also the button to 'confirm' and actually change the entered text of my label is on form 2 which needs to stay that way.
for some reason this does not work.
Form 2 has a text-box and a button, when I press the button, it changes the string value of the designated string.
This string is linked to a label on form 1. the string is being changed so that is not the problem I confirmed this by a adding a button which pops up a message box showing the new string value.
While searching for an answer I found that is must be some sort of refreshing problem, I tried a lot of methods with no success. Only methods that did work where those who would put my button onto form 1 instead of 2.
I've been googling for 3 hours straight on how to fix this problem but either the methods don't work or they change my button from form 2 to my main form (form 1).
Please don't call me lazy I really can't find a method that works!
EDIT:
Code
GameScreen.cs
namespace _2pGame
{
public partial class GameScreen : Form
{
public GameScreen()
{
InitializeComponent();
P1NameLabel.Text = gm.P1Name;
P1ClassLabel.Text = gm.P1Class;
P2NameLabel.Text = gm.P2Name;
P2ClassLabel.Text = gm.P2Class;
}
private void PlayerInfoButton_Click(object sender, EventArgs e)
{
PlayerInfo playerinfoload = new PlayerInfo();
playerinfoload.Show();
}
}
}
PlayerInfo.cs
namespace _2pGame
{
public partial class PlayerInfo : Form
{
public PlayerInfo()
{
InitializeComponent();
}
public void ConfirmPlayerInfo_Click(object sender, EventArgs e)
{
gm.P1Class = P1ClassChoice.Text;
gm.P1Name = P1TextBox.Text;
gm.P2Class = P2ClassChoice.Text;
gm.P2Name = P2TextBox.Text;
}
}
}
Refs.cs
namespace _2pGame
{
public partial class gm
{
public static string
P1Class,
P2Class,
P1Name,
P2Name;
}
}
An approach to this very well know situation is through delegates....
In your PlayerInfo form declare
public partial class PlayerInfo : Form
{
// define the delegate type (a parameterless method that returns nothing)
public delegate void OnConfirmPlayer();
// declare a public variable of that delegate type
public OnConfirmPlayer PlayerConfirmed;
.....
public void ConfirmPlayerInfo_Click(object sender, EventArgs e)
{
gm.P1Class = P1ClassChoice.Text;
gm.P1Name = P1TextBox.Text;
gm.P2Class = P2ClassChoice.Text;
gm.P2Name = P2TextBox.Text;
// Check is someone is interested to be informed of this change
// If someone assign a value to the public delegate variable then
// you have to call that method to let the subscriber know
if (PlayerConfirmed != null)
PlayerConfirmed();
}
}
Then in your GameScreen form, just before showing the PlayerInfo form, set the public PlayerInfo.PlayerConfirmed to a method into the GameScreen form class
private void PlayerInfoButton_Click(object sender, EventArgs e)
{
PlayerInfo playerinfoload = new PlayerInfo();
// Subscribe to the notification from PlayerInfo instance
playerinfoload.PlayerConfirmed += PlayerHasBeenConfirmed;
playerinfoload.Show();
}
// Method that receives the notification from PlayerInfo
private void PlayerHasBeenConfirmed()
{
P1NameLabel.Text = gm.P1Name;
P1ClassLabel.Text = gm.P1Class;
P2NameLabel.Text = gm.P2Name;
P2ClassLabel.Text = gm.P2Class;
}
This approach has the advantage to avoid a coupling between the GameScreen and the PlayerInfo. No need to know inside the PlayerInfo the existance of a GameScreen form and the name of its properties. You just publish a delegate that a subscriber could register to be informed of the changes and let the subscriber acts on its own code.
You need a reference to your main form and assign the textbox values each time they need to be updated.
public partial class PlayerInfo : Form
{
private readonly GameScreen _main;
public PlayerInfo(GameScreen main)
{
_main = main;
InitializeComponent();
}
public void ConfirmPlayerInfo_Click(object sender, EventArgs e)
{
gm.P1Class = P1ClassChoice.Text;
gm.P1Name = P1TextBox.Text;
gm.P2Class = P2ClassChoice.Text;
gm.P2Name = P2TextBox.Text;
main.P1NameLabel.Text = gm.P1Name;
main.P1ClassLabel.Text = gm.P1Class;
main.P2NameLabel.Text = gm.P2Name;
main.P2ClassLabel.Text = gm.P2Class;
}
}
You also need to pass the reference when the PlayerInfo form is created
private void PlayerInfoButton_Click(object sender, EventArgs e)
{
PlayerInfo playerinfoload = new PlayerInfo(this); //pass ref to self
playerinfoload.Show();
}
Note that there are other better ways to do this, but this is the easiest that I can think of.
You can probably look at events or Mediator pattern if you want something better.
Related
I have a winform called Form1 and a textbox called textBox1
In the Form1 I can set the text by typing:
textBox1.text = "change text";
Now I have created another class. How do I call textBox1 in this class?
so I want to change the text for textBox1 in this class.
How can I access the Form1 from this new class?
I would recommend that you don't. Do you really want to have a class that is dependent on how the text editing is implemented in the form, or do you want a mechanism allowing you to get and set the text?
I would suggest the latter. So in your form, create a property that wraps the Text property of the TextBox control in question:
public string FirstName
{
get { return firstNameTextBox.Text; }
set { firstNameTextBox.Text = value; }
}
Next, create some mechanism through which you class can get a reference to the form (through the contructor for instance). Then that class can use the property to access and modify the text:
class SomeClass
{
private readonly YourFormClass form;
public SomeClass(YourFormClass form)
{
this.form = form;
}
private void SomeMethodDoingStuffWithText()
{
string firstName = form.FirstName;
form.FirstName = "some name";
}
}
An even better solution would be to define the possible interactions in an interface, and let that interface be the contract between your form and the other class. That way the class is completely decoupled from the form, and can use anyting implementing the interface (which opens the door for far easier testing):
interface IYourForm
{
string FirstName { get; set; }
}
In your form class:
class YourFormClass : Form, IYourForm
{
// lots of other code here
public string FirstName
{
get { return firstNameTextBox.Text; }
set { firstNameTextBox.Text = value; }
}
}
...and the class:
class SomeClass
{
private readonly IYourForm form;
public SomeClass(IYourForm form)
{
this.form = form;
}
// and so on
}
I was also facing the same problem where I was not able to appendText to richTextBox of Form class. So I created a method called update, where I used to pass a message from Class1.
class: Form1.cs
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
_Form1 = this;
}
public static Form1 _Form1;
public void update(string message)
{
textBox1.Text = message;
}
private void Form1_Load(object sender, EventArgs e)
{
Class1 sample = new Class1();
}
}
class: Class1.cs
public class Class1
{
public Class1()
{
Form1._Form1.update("change text");
}
}
You can change the access modifier for the generated field in Form1.Designer.cs from private to public. Change this
private System.Windows.Forms.TextBox textBox1;
by this
public System.Windows.Forms.TextBox textBox1;
You can now handle it using a reference of the form Form1.textBox1.
Visual Studio will not overwrite this if you make any changes to the control properties, unless you delete it and recreate it.
You can also chane it from the UI if you are not confortable with editing code directly. Look for the Modifiers property:
public partial class Form1 : Form
{
public static Form1 gui;
public Form1()
{
InitializeComponent();
gui = this;
}
public void WriteLog(string log)
{
this.Invoke(new Action(() => { txtbx_test1.Text += log; }));
}
}
public class SomeAnotherClass
{
public void Test()
{
Form1.gui.WriteLog("1234");
}
}
I like this solution.
You will need to have some access to the Form's Instance to access its Controls collection and thereby changing the Text Box's Text.
One of ways could be that You can have a Your Form's Instance Available as Public or More better Create a new Constructor For your Second Form and have it receive the Form1's instance during initialization.
Define a property of the form like, then use this in other places it would be available with the form instance
public string SetText
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
If your other class inherits Form1 and if your textBox1 is declared public, then you can access that text box from your other class by simply calling:
otherClassInstance.textBox1.Text = "hello world";
Use, a global variable or property for assigning the value to the textbox, give the value for the variable in another class and assign it to the textbox.text in form class.
I Found an easy way to do this,I've tested it,it works Properly.
First I created a Windows Project,on the form I Inserted a TextBox and I named it textBox1
then I inserted a button named button1,then add a class named class1.
in the class1 I created a TextBox:
class class1
{
public static TextBox txt1=new TextBox(); //a global textbox to interfece with form1
public static void Hello()
{
txt1.Text="Hello";
}
}
Now in your Form Do this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
class1.txt1=textBox1;
class1.Hello();
}
}
in the button1_Click I coppied the object textBox1 into txt1,so now txt1 has the properties
of textBox1 and u can change textBox1 text in another form or class.
Form1 form = new Form1();
form.textBox1.Text = "test";
I tried the examples above, but none worked as described. However, I have a solution that is combined from some of the examples:
public static Form1 gui;
public Form1()
{
InitializeComponent();
gui = this;
comms = new Comms();
}
public Comms()
{
Form1.gui.tsStatus.Text = "test";
Form1.gui.addLogLine("Hello from Comms class");
Form1.gui.bn_connect.Text = "Comms";
}
This works so long as you're not using threads. Using threads would require more code and was not needed for my task.
I used this method for updating a label but you could easily change it to a textbox:
Class:
public Class1
{
public Form_Class formToOutput;
public Class1(Form_Class f){
formToOutput = f;
}
// Then call this method and pass whatever string
private void Write(string s)
{
formToOutput.MethodToBeCalledByClass(s);
}
}
Form methods that will do the updating:
public Form_Class{
// Methods that will do the updating
public void MethodToBeCalledByClass(string messageToSend)
{
if (InvokeRequired) {
Invoke(new OutputDelegate(UpdateText),messageToSend);
}
}
public delegate void OutputDelegate(string messageToSend);
public void UpdateText(string messageToSend)
{
label1.Text = messageToSend;
}
}
Finally
Just pass the form through the constructor:
Class1 c = new Class1(this);
Form frm1 = new Form1();
frm1.Controls.Find("control_name",true)[0].Text = "I changed this from another form";
// Take the Active form to a form variable.
Form F1 = myForm1.ActiveForm;
//Findout the Conntrol and Change the properties
F1.Controls.Find("Textbox1", true).ElementAt(0).Text= "Whatever you want to write";
What about
Form1.textBox1.text = "change text";
note:
1. you have to "include" Form1 to your second form source file by
using Form1;
textBox1 should be public
I have a main form (let's call it frmHireQuote) that is a child of a main MDI form (frmMainMDI), that shows another form (frmImportContact) via ShowDialog() when a button is clicked.
When the user clicks the 'OK' on frmImportContact, I want to pass a few string variables back to some text boxes on frmHireQuote.
Note that there could be multiple instances of frmHireQuote, it's obviously important that I get back to the instance that called this instance of frmImportContact.
What's the best method of doing this?
Create some public Properties on your sub-form like so
public string ReturnValue1 {get;set;}
public string ReturnValue2 {get;set;}
then set this inside your sub-form ok button click handler
private void btnOk_Click(object sender,EventArgs e)
{
this.ReturnValue1 = "Something";
this.ReturnValue2 = DateTime.Now.ToString(); //example
this.DialogResult = DialogResult.OK;
this.Close();
}
Then in your frmHireQuote form, when you open the sub-form
using (var form = new frmImportContact())
{
var result = form.ShowDialog();
if (result == DialogResult.OK)
{
string val = form.ReturnValue1; //values preserved after close
string dateString = form.ReturnValue2;
//Do something here with these values
//for example
this.txtSomething.Text = val;
}
}
Additionaly if you wish to cancel out of the sub-form you can just add a button to the form and set its DialogResult to Cancel and you can also set the CancelButton property of the form to said button - this will enable the escape key to cancel out of the form.
I normally create a static method on form/dialog, that I can call. This returns the success (OK-button) or failure, along with the values that needs to be filled in.
public class ResultFromFrmMain {
public DialogResult Result { get; set; }
public string Field1 { get; set; }
}
And on the form:
public static ResultFromFrmMain Execute() {
using (var f = new frmMain()) {
var result = new ResultFromFrmMain();
result.Result = f.ShowDialog();
if (result.Result == DialogResult.OK) {
// fill other values
}
return result;
}
}
To call your form;
public void MyEventToCallForm() {
var result = frmMain.Execute();
if (result.Result == DialogResult.OK) {
myTextBox.Text = result.Field1; // or something like that
}
}
Found another small problem with this code... or at least it was problematic when I tried to implement it.
The buttons in frmMain do not return a compatible value, using VS2010 I added the following and everything started working fine.
public static ResultFromFrmMain Execute() {
using (var f = new frmMain()) {
f.buttonOK.DialogResult = DialogResult.OK;
f.buttonCancel.DialogResult = DialogResult.Cancel;
var result = new ResultFromFrmMain();
result.Result = f.ShowDialog();
if (result.Result == DialogResult.OK) {
// fill other values
}
return result;
}
}
After adding the two button values, the dialog worked great!
Thanks for the example, it really helped.
delegates are the best option for sending data from one form to another.
public partial class frmImportContact : Form
{
public delegate void callback_data(string someData);
public event callback_data getData_CallBack;
private void button_Click(object sender, EventArgs e)
{
string myData = "Top Secret Data To Share";
getData_CallBack(myData);
}
}
public partial class frmHireQuote : Form
{
private void Button_Click(object sender, EventArgs e)
{
frmImportContact obj = new frmImportContact();
obj.getData_CallBack += getData;
}
private void getData(string someData)
{
MessageBox.Show("someData");
}
}
I just put into constructor something by reference, so the subform can change its value and main form can get new or modified object from subform.
If you want to pass data to form2 from form1 without passing like new form(sting "data");
Do like that
in form 1
using (Form2 form2= new Form2())
{
form2.ReturnValue1 = "lalala";
form2.ShowDialog();
}
in form 2 add
public string ReturnValue1 { get; set; }
private void form2_Load(object sender, EventArgs e)
{
MessageBox.Show(ReturnValue1);
}
Also you can use value in form1 like this if you want to swap something in form1
just in form1
textbox.Text =form2.ReturnValue1
I use MDI quite a lot, I like it much more (where it can be used) than multiple floating forms.
But to get the best from it you need to get to grips with your own events. It makes life so much easier for you.
A skeletal example.
Have your own interupt types,
//Clock, Stock and Accoubts represent the actual forms in
//the MDI application. When I have multiple copies of a form
//I also give them an ID, at the time they are created, then
//include that ID in the Args class.
public enum InteruptSource
{
IS_CLOCK = 0, IS_STOCKS, IS_ACCOUNTS
}
//This particular event type is time based,
//but you can add others to it, such as document
//based.
public enum EVInterupts
{
CI_NEWDAY = 0, CI_NEWMONTH, CI_NEWYEAR, CI_PAYDAY, CI_STOCKPAYOUT,
CI_STOCKIN, DO_NEWEMAIL, DO_SAVETOARCHIVE
}
Then your own Args type
public class ControlArgs
{
//MDI form source
public InteruptSource source { get; set; }
//Interrupt type
public EVInterupts clockInt { get; set; }
//in this case only a date is needed
//but normally I include optional data (as if a C UNION type)
//the form that responds to the event decides if
//the data is for it.
public DateTime date { get; set; }
//CI_STOCKIN
public StockClass inStock { get; set; }
}
Then use the delegate within your namespace, but outside of a class
namespace MyApplication
{
public delegate void StoreHandler(object sender, ControlArgs e);
public partial class Form1 : Form
{
//your main form
}
Now either manually or using the GUI, have the MDIparent respond to the events of the child forms.
But with your owr Args, you can reduce this to a single function. and you can have provision to interupt the interupts, good for debugging, but can be usefull in other ways too.
Just have al of your mdiparent event codes point to the one function,
calendar.Friday += new StoreHandler(MyEvents);
calendar.Saturday += new StoreHandler(MyEvents);
calendar.Sunday += new StoreHandler(MyEvents);
calendar.PayDay += new StoreHandler(MyEvents);
calendar.NewYear += new StoreHandler(MyEvents);
A simple switch mechanism is usually enough to pass events on to appropriate forms.
First you have to define attribute in form2(child) you will update this attribute in form2 and also from form1(parent) :
public string Response { get; set; }
private void OkButton_Click(object sender, EventArgs e)
{
Response = "ok";
}
private void CancelButton_Click(object sender, EventArgs e)
{
Response = "Cancel";
}
Calling of form2(child) from form1(parent):
using (Form2 formObject= new Form2() )
{
formObject.ShowDialog();
string result = formObject.Response;
//to update response of form2 after saving in result
formObject.Response="";
// do what ever with result...
MessageBox.Show("Response from form2: "+result);
}
I raise an event in the the form setting the value and subscribe to that event in the form(s) that need to deal with the value change.
I have two Forms: MainForm and OptionsForm, wich has a button (OK) that applies the some changes on MainForm. When I open the OptionsForm for the first time everything is ok, with the default values.
After I make some changes and and click OK the options are applied but when I open the OptionsForm for the second time, I wanted to hold the previous values, not the default ones like its happening.
OptionsForm is opened through MainForm like this
OptionsForm formOptions = new OptionsForm();
if (formOptions.ShowDialog(this) == DialogResult.OK)
{
// etc..
}
//...
public string otherLabel
{
get { return formMainLabel.Text; }
set { formMainLabel.Text = value; }
}
In OptionsForm I have a NumericUpDown and want to hold its value
private MainForm mainForm = null;
public OptionsForm(Form callingForm)
{
mainForm = callingForm as MainForm;
InitializeComponent();
}
// ...
private void btnOK_Click(object sender, EventArgs e)
{
this.mainForm.someLabel= someBox.Value.ToString(); // NumericUpDown
this.mainForm.otherLabel = "abc"; //>>> Getting NullReferenceException
this.Close();
}
Now I can hold my settings but I'm getting a NullReferenceException. I tryed this but it's still not working. Any sugestion?
ShowDialog() was already made to support this. It is different from Show(), other than it being modal, it also prevents the form object from being disposed when the user closes it. So you can simply call ShowDialog() again, the controls keep their original values:
private OptionsForm options = new OptionsForm();
private void button1_Click(object sender, EventArgs e) {
if (options.ShowDialog(this) == DialogResult.OK) {
// etc..
}
}
protected override void OnFormClosed(FormClosedEventArgs e) {
options.Dispose();
base.OnFormClosed(e);
}
Well, you should pass these values to OptionsForm, feel free to write custom constructor for OpptionsForm and call it when you need.
One way to do it would be to just always keep a reference to your FormOptions and show the same instance rather than creating a new one every time. Or, if you don't want to do that, you can create an Options class that stores all of your options, which can then be stored and passed into any new instance you create thereafter. There's advantages and disadvantages to both so feel free to choose the option that best suits your needs.
public class MyOptions
{
public String StringOption { get; set; }
public int IntOption { get; set; }
}
Your FormOptions would then have a MyOptions property where you can set all of your options and retrieve them.
public class FormOptions : Form
{
...
private MyOptions _options;
public MyOptions Options
{
get { return _options;}
set
{
_options = value;
// Set the Form's control values accordingly.
}
}
...
}
And finally, you would call it like so in your code:
FormOptions optionsForm = new FormOptions();
MyOptions savedOptions = new MyOptions(); // Probably don't want to create a new instance every time but I'm sure you get the idea here.
optionsForm.Options = savedOptions;
optionsForm.ShowDialog();
// Get the new options after the form is closed.
savedOptions = optionsForm.Options;
if you just want to keep only one numeric up/down control's value, then just pass it as a parameter in the constructor..
public FormOptions(MainForm -mainFrm, int curNumericValue)
{
someBox.value = curNumericValue;
}
and instantiate the form with the value from the MainForm
private void button1_click(....)
{
FormOptions formOptions = new FormOptions(this, Convert.toInt32(someLabel.text));
formOptions.ShowDialog();
}
Why not just make use of the "Settings" that are available within the build properties, and WinForms itself? Just have your settings form populate itself with these variables, and "set" them when you click OK. Then have the MainForm refresh from these settings once the SettingsForm has fully closed. Easy, no mess, and no passing variables between forms.
Overview: http://msdn.microsoft.com/en-us/library/k4s6c3a0.aspx
SO Question covering Settings: Save Settings in a .NET Winforms Application
It also has the added bonus that the values will be saved between sessions of the application.
Seems like you are calling an instance of the options form from a click event like this:
button1_click(object sender, EventArgs e)
{
OptionsForm optForm = new OptionsForm();
optForm.showDialog();
}
You have to create variable for the options form class within the Mainform class, instantiate it there, or in the constructor, and only call the ShowDialog() or Show() method within the button_Click event. Like this:
partial class MainForm:Form
{
OptionsForm optForm;
............
............
public MainForm() //Constructor
{
initialiseComponent();
optForm = new OptionsForm();
........
}
.......
private button1_Click(object sender, EventArgs e)
{
optForm.Show(); // or ShowDialog()
}
}
and use this.hide() instead of this.close() in the options form.. or else the form gets disposed..
I'm a beginner at C# who's decided to create a textbased adventure game in a Winform, but I've been struggling with updating the form whenever it needs to update. In the past, I have used something.Invalidate(); to update an image, but apparently that doesn't work for an entire form.
I have a set of labels that display text based on an integer and whenever the value of the integer updates, I'd like the form to show that.
What I have tried thus far:
public partial class GameWindow : Form
{
public void buttonInventory_Click(object sender, EventArgs e)
{
Basic.HP = Basic.HP++;
this.Refresh();
}
}
While the HP updates, the form doesn't show it. Is there anything else I should use than Refresh();? A lot of googling mostly resulted in explanations about Backgroundworkers, but do I really need another thread for something as simple as this?
Why not just make a separate routine for updating values, that you call after every value change. IE: (Note - I don't program in C#):
public partial class GameWindow : Form
{
public void buttonInventory_Click(object sender, EventArgs e)
{
Basic.HP = Basic.HP++;
updateValues();
}
public void updateValues()
{
hp.text = HealthInteger;
basic.text = BasicInteger;
}
}
And call this for evey value change.
A label can't be bind to a string value like an image can be to a picture box.
The simplest solution here is too explicitly set the Text property of the label each time your HP property is changed :
private void RefreshFormWithModel(Basic basic)
{
labelHP.Text = basic.HP;
}
public void buttonInventory_Click(object sender, EventArgs e)
{
Basic.HP = Basic.HP++;
this.RefreshFormWithModel(Basic);
}
If you really want complex binding, here is some lectures.
I'm going to assume the class name of Basic is just Basic
in the class Basic
private int hp;
public int HP
{
get { return hp; }
set { hp = value; HP_Changed(); }
}
public event EventHandler HPChanged;
private void HP_Changed()
{
if (HPChanged != null) { HPChanged(this, new EventArgs()); }
}
in the GameWindow
//where ever you create a new Basic, add to the event handler
Basic Basic = new Basic();
Basic.HPChanged += Basic_HPChanged;
private void Basic_HPChanged(object sender, EventArgs e)
{
Basic b_sender = (Basic)sender;
int NewHealth = b_sender.HP;
//Update whatever value needs to be updated, here
}
Then whenever the HP of the Basic is changed, it will fire an event in the GameWindow to update the appropriate field.
I have a main form (let's call it frmHireQuote) that is a child of a main MDI form (frmMainMDI), that shows another form (frmImportContact) via ShowDialog() when a button is clicked.
When the user clicks the 'OK' on frmImportContact, I want to pass a few string variables back to some text boxes on frmHireQuote.
Note that there could be multiple instances of frmHireQuote, it's obviously important that I get back to the instance that called this instance of frmImportContact.
What's the best method of doing this?
Create some public Properties on your sub-form like so
public string ReturnValue1 {get;set;}
public string ReturnValue2 {get;set;}
then set this inside your sub-form ok button click handler
private void btnOk_Click(object sender,EventArgs e)
{
this.ReturnValue1 = "Something";
this.ReturnValue2 = DateTime.Now.ToString(); //example
this.DialogResult = DialogResult.OK;
this.Close();
}
Then in your frmHireQuote form, when you open the sub-form
using (var form = new frmImportContact())
{
var result = form.ShowDialog();
if (result == DialogResult.OK)
{
string val = form.ReturnValue1; //values preserved after close
string dateString = form.ReturnValue2;
//Do something here with these values
//for example
this.txtSomething.Text = val;
}
}
Additionaly if you wish to cancel out of the sub-form you can just add a button to the form and set its DialogResult to Cancel and you can also set the CancelButton property of the form to said button - this will enable the escape key to cancel out of the form.
I normally create a static method on form/dialog, that I can call. This returns the success (OK-button) or failure, along with the values that needs to be filled in.
public class ResultFromFrmMain {
public DialogResult Result { get; set; }
public string Field1 { get; set; }
}
And on the form:
public static ResultFromFrmMain Execute() {
using (var f = new frmMain()) {
var result = new ResultFromFrmMain();
result.Result = f.ShowDialog();
if (result.Result == DialogResult.OK) {
// fill other values
}
return result;
}
}
To call your form;
public void MyEventToCallForm() {
var result = frmMain.Execute();
if (result.Result == DialogResult.OK) {
myTextBox.Text = result.Field1; // or something like that
}
}
Found another small problem with this code... or at least it was problematic when I tried to implement it.
The buttons in frmMain do not return a compatible value, using VS2010 I added the following and everything started working fine.
public static ResultFromFrmMain Execute() {
using (var f = new frmMain()) {
f.buttonOK.DialogResult = DialogResult.OK;
f.buttonCancel.DialogResult = DialogResult.Cancel;
var result = new ResultFromFrmMain();
result.Result = f.ShowDialog();
if (result.Result == DialogResult.OK) {
// fill other values
}
return result;
}
}
After adding the two button values, the dialog worked great!
Thanks for the example, it really helped.
delegates are the best option for sending data from one form to another.
public partial class frmImportContact : Form
{
public delegate void callback_data(string someData);
public event callback_data getData_CallBack;
private void button_Click(object sender, EventArgs e)
{
string myData = "Top Secret Data To Share";
getData_CallBack(myData);
}
}
public partial class frmHireQuote : Form
{
private void Button_Click(object sender, EventArgs e)
{
frmImportContact obj = new frmImportContact();
obj.getData_CallBack += getData;
}
private void getData(string someData)
{
MessageBox.Show("someData");
}
}
I just put into constructor something by reference, so the subform can change its value and main form can get new or modified object from subform.
If you want to pass data to form2 from form1 without passing like new form(sting "data");
Do like that
in form 1
using (Form2 form2= new Form2())
{
form2.ReturnValue1 = "lalala";
form2.ShowDialog();
}
in form 2 add
public string ReturnValue1 { get; set; }
private void form2_Load(object sender, EventArgs e)
{
MessageBox.Show(ReturnValue1);
}
Also you can use value in form1 like this if you want to swap something in form1
just in form1
textbox.Text =form2.ReturnValue1
I use MDI quite a lot, I like it much more (where it can be used) than multiple floating forms.
But to get the best from it you need to get to grips with your own events. It makes life so much easier for you.
A skeletal example.
Have your own interupt types,
//Clock, Stock and Accoubts represent the actual forms in
//the MDI application. When I have multiple copies of a form
//I also give them an ID, at the time they are created, then
//include that ID in the Args class.
public enum InteruptSource
{
IS_CLOCK = 0, IS_STOCKS, IS_ACCOUNTS
}
//This particular event type is time based,
//but you can add others to it, such as document
//based.
public enum EVInterupts
{
CI_NEWDAY = 0, CI_NEWMONTH, CI_NEWYEAR, CI_PAYDAY, CI_STOCKPAYOUT,
CI_STOCKIN, DO_NEWEMAIL, DO_SAVETOARCHIVE
}
Then your own Args type
public class ControlArgs
{
//MDI form source
public InteruptSource source { get; set; }
//Interrupt type
public EVInterupts clockInt { get; set; }
//in this case only a date is needed
//but normally I include optional data (as if a C UNION type)
//the form that responds to the event decides if
//the data is for it.
public DateTime date { get; set; }
//CI_STOCKIN
public StockClass inStock { get; set; }
}
Then use the delegate within your namespace, but outside of a class
namespace MyApplication
{
public delegate void StoreHandler(object sender, ControlArgs e);
public partial class Form1 : Form
{
//your main form
}
Now either manually or using the GUI, have the MDIparent respond to the events of the child forms.
But with your owr Args, you can reduce this to a single function. and you can have provision to interupt the interupts, good for debugging, but can be usefull in other ways too.
Just have al of your mdiparent event codes point to the one function,
calendar.Friday += new StoreHandler(MyEvents);
calendar.Saturday += new StoreHandler(MyEvents);
calendar.Sunday += new StoreHandler(MyEvents);
calendar.PayDay += new StoreHandler(MyEvents);
calendar.NewYear += new StoreHandler(MyEvents);
A simple switch mechanism is usually enough to pass events on to appropriate forms.
First you have to define attribute in form2(child) you will update this attribute in form2 and also from form1(parent) :
public string Response { get; set; }
private void OkButton_Click(object sender, EventArgs e)
{
Response = "ok";
}
private void CancelButton_Click(object sender, EventArgs e)
{
Response = "Cancel";
}
Calling of form2(child) from form1(parent):
using (Form2 formObject= new Form2() )
{
formObject.ShowDialog();
string result = formObject.Response;
//to update response of form2 after saving in result
formObject.Response="";
// do what ever with result...
MessageBox.Show("Response from form2: "+result);
}
I raise an event in the the form setting the value and subscribe to that event in the form(s) that need to deal with the value change.