I get two return variables from a user control back.
I want to use these variables in the main form and in a next user control.
Unfortunately I can't seem to get them into my main form.
User control where the variables come from:
try
{
this.Visible = false;
textBox1.Clear();
textBox2.Clear();
Dashboard frm2 = new Dashboard(name , rechte);
}
And the main Form receives the variables but I donĀ“t get how to continue accessing them (like label3.Text = .... ):
public Dashboard(object name, object rechte)
{
this.BN =Convert.ToString(name);
this.brechte =Convert.ToString(rechte);
}
Related
I'm trying to pass a variable from one form to another form textbox. The 'variable' is a result of a calculation based on the user inputs.
Below is the code for the parent form(RuleInsertForm) where I'm calling the subform(Helpformula) to get the user inputs.
public partial class RuleInsertForm : Form
{
public string helpformulainputs;
}
private void RuleInsertForm_Load(object sender,EventArgs e)
{
if (helpformulainputs=="")
{
textBox_Inputs.Text = "";
}
else
{
textBox_Inputs.Text = helpformulainputs;
}
}
Below is the code for the subform(Helpformula) where i'm passing the result variable(formulainputs) to the parent form(RuleInsertForm).
public partial class HelpFormula : Form
{
public string formulainputs = string.Empty;
private void button_generateformula_Click(objectsender, EventArgs e)
{
using (RuleInsertForm insertform = new RuleInsertForm())
{
insertform.helpformulainputs = formulainputs;
this.Close();
insertform.Show();
}
}
}
Problem:
The values are getting passed to the text box but in the UI its not getting dispalyed.
so far I tried to push data back to parent form and then tried to display the data in the textbox where I failed.(I dont know where it went wrong suggest me if I can resolve the below one)
Now I need an alternative method to this for eg: instead of pushing the data back to parent form i need to make the variable available for all the forms trying to use the subform(formulainputs)
How can I acheive this process ? any suggestions are much appreciated.
The problem seems to be that insertForm.Show() does not block the execution of your button handler. Show opens the insertform as non-modal.
So after insertform is opened, the execution is continued in button_generateformula_Click and when you exit the using block, the insertform is disposed and therefore closed.
To solve this you may call insertForm.ShowDialog() instead.
For different ways of communicating between Forms look here or simply type communicate between forms into the SO search box.
I'm trying to change the interval value of a timer (in Form1) from my settings form.
I'm declaring the form1 with static Form1 formInstance;
But it throws null exception on forminstance when i change the value.
I've also tried Form1 form1 = new Form1(); but the application crashes when i open settings form. Note that i've already have timer modifier set to public.
public partial class SettingsForm : Form
{
static Form1 formInstance;
...
if (Properties.Settings.Default.sync != Convert.ToInt32(textBox1.Text))
{
formInstance.timer1.Stop();
formInstance.timer1.Interval = 60000;
formInstance.timer1.Start();
}
It seems you have two classes:
A class Form1 that has a timer that you want to change,
A settings Form where you want to set the timer in Form1
In windows it is more common to let the form remember all changed settings, until the operator presses OK or Cancel, instead of updating the setting as soon as the operator changes the value.
Advantage: the operator can change the value several times, or even press a Cancel button. Only if the OK button is pressed the time value will be set.
Advantage: if the settings form controls several settings that relate to each other it is much easier to check for validity of the changed values when the operator expresses he is finishing changing the value when he presses OK
Disadvantage: the operator doesn't know the effect of the changed value until he presses OK.
This disadvantage can be solved by offering an Apply Now button.
Note that the OK / Cancel / Apply Now is standard Windows behaviour. Everyone will know what will happen, while a method that changes some settings of your form immediately and some not might be confusing.
Having said this, I assume the following:
Upon some event (probably clicking a button, or selecting a menu item) the form decides that it is time to show its settings Form.
The operator changes zero or more settings and presses OK or Cancel
If the operator pressed OK the main form is informed. It will ask the settings form for the settings and update his settings accordingly.
So let's make an example:
We have a Form1 with a button1 and a timer1, It has several settings, for instance TimerTimeout, Setting1 and Setting2.
If the operator clicks button1, then the settings form is shown.
Initially the settings form shows the current values of the timerTimeout, Setting1 and Setting2.
The operator can change the values of any of these settings.
When he finishes, he can click Cancel or Ok
The code is as follows:
public class SettingsForm : Form
{
public TimeSpan TimerTime {get; set;}
public int Setting1 {get; set;}
public string Setting2 {get; set;}
public void OnButtonOk_Clicked(object sender, ...)
{
if (!this.AllValuesOk())
{ // error in one of the values
// show message box
}
else
{
this.Close();
}
}
}
Now Let's show the settings form when button1 is clicked on Form1:
private void OnButton1_Clicked(object sender, ...)
{
using (var settingsForm = new SettingsForm)
{
settingsForm.TimerTime = this.TimerTime;
settingsForm.Setting1 = this.Setting1;
settingsForm.Setting2 = this.Setting2;
// now that the settings form is initialized
// we can show it and wait until the user closes the form
var dlgResult = settingsForm.ShowDialog(this);
// only use the new settings if the operator pressed OK:
if (dlgResult == DialogResult.OK)
{
this.TimerTime = settingsForm.TimerTime;
this.Setting1 = settingsForm.Setting1;
this.Setting2 = settingsForm.Setting2;
this.ProcessChangedSettings();
}
}
}
Note that the settings form doesn't have to know anything about Form1. This enables it to use the settings form for any form that has a TimerTimer, a Setting1 and a Setting2.
Do you also notice how easy it is to use the original settings if the user presses Cancel, or presses the cross in the upper right corner of the settings form or presses alt-F4, or whatever method he can use to cancel.
Also note that during changing, the operator can have incompabible settings, for instance a halve finished string, an incorrect timer time etc. Only the moment he presses OK the software checks if all values are filled in correctly.
pass form1 as parameter on the constructor of settingForm
private Form1 _objForm1;
public SettingForm (Form1 objForm1)
{
_objForm1 = objForm1;
}
Private ButtonClicked(sender,...)
{
_objForm1.timer1.Stop();
_objForm1.timer1.Interval = 60000;
_objForm1.timer1.Start();
}
Use properties in Form1 and access it from another form.. In Setting form create a private variable for example:
private int interval;
create a getter setter method:
public int Interval
{
get { return interval; }
set { interval = value; }
}
Then in SettingsForm return a this.DialogResult = DialogResult.OK; dialog result at the method end, for example at the end of the button click event.
In Form1 when you open the SettingsForm you can access the value set in SettingsForm:
if(settingsForm.ShowDialog() == DialogResults.OK)
{
timer1.Interval = settingsForm.Interval;
}
If you want to access the timer but not from an instance,
Form1.timer.Interval = 4;
you would have to go into "Form1.designer.cs" and find where it says
public Timer timer1;
and change it to
public static Timer timer1;
I have the following snippet of code that allows me to pull the properties from an object in my list and assign them to variables in other forms. However, I need to be able to pull the data from my variables in the other form and use those to set the properties of the given object.
My class Account is used to populate my list accounts. On my next form AccountMenu I have a class Variables1 that contains accessible variables that are used throughout the rest of my forms to keep track of the checking balance and saving balance. When logging off from the AccountMenu, I want to be able to pass the values from Variables1 to the account that was initially used.
I know how to pass variables from one form to another, but I'm not really sure how to update the form automatically, without a button, on the original form. Thus, the solution that I see is that I have a button on my AccountMenu form that "logs" the user out, via this.close(); Additionally, I guessed that under that button, I need to have some code that assigns the variables as properties to the object. I'm just not sure how I can access the set properties of the object, since it is dynamically called with the code below.
Can someone help me figure out what I need to do? Below is some of the relevant code so that you can see how I have things set up. I am just not sure how to access "matches" from the other form in order to update that specific object properties. Thank you, anyone, who can help!
//variable that will be used to check textbox1.Text
string stringToCheck;
//array of class Account
List<Account> accounts = new List<Account>();
public MainMenu()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//set value to user's input
stringToCheck = textBox1.Text;
//set a var that only returns a value if the .Name already exists
var matches = accounts.FirstOrDefault(p => p.Name == stringToCheck);
//check through each element of the array
if (matches == null)
{
accounts.Add(new Account(stringToCheck));
textBox1.Text = "";
label3.Visible = true;
}
else if (matches != null)
{
//set variables in another form. not sure if these are working
Variables1.selectedAccount = matches.Name;
//is this calling the CheckBalance of the instance?
Variables1.selectedCheckBalance = matches.CheckBalance;
//same thing?
Variables1.selectedSaveBalance = matches.SaveBalance;
//switch to form
AccountMenu acctMenu = new AccountMenu();
this.Hide();
acctMenu.Show();
}
}
As per my understanding I think what you required is kind of trigger on your parent form that needs to be called from your child application.
If that is what you required than you can go with defining an event on your AccountMenu form. and register this event from your Accounts form.
Than simply raise this event from your AccountMenu subform.
Deletegates and Events are really works like magic :)
Let me show you some code how to do this.
Code required in AccountMenu window:
public delegate void PassDataToAccounts(string result);
public event PassDataToAccounts OnPassDataToAccount;
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
if (OnPassDataToAccount != null)
OnPassDataToAccount("result");
base.OnClosing(e);
}
Code required in Accounts window button1_Click event where the AccountMenu will open:
//set variables in another form. not sure if these are working
Variables1.selectedAccount = matches.Name;
//is this calling the CheckBalance of the instance?
Variables1.selectedCheckBalance = matches.CheckBalance;
//same thing?
Variables1.selectedSaveBalance = matches.SaveBalance;
//switch to form
AccountMenu acctMenu = new AccountMenu();
acctMenu..OnPassDataToAccount += childwindow_OnPassDataToAccount;
this.Hide();
acctMenu.Show();
}
void childwindow_OnPassDataToAccount(string result)
{
if (result == "result")
{
// Processing required on your parent window can be caried out here
//Variables1 can be processed directly here.
}
}
Im making a game with a menu that opens new forms for each level. When you complete a level, it is supposed to congratulate you through a message box (it does) and then enable the next level's button on the different menu form. So I accessed the designer and made the buttons public and tried:
new LevelMenu().button2.Enabled = true;
But that didn't work.
I also tried doing:
public event Action levelCompleted;
//then down lower i did (after it is declared that you won the level):
if (levelCompleted != null)
levelCompleted();
W1L1.levelCompleted += () => LevelMenu.button2.Enabled = true;
But that give me the error of:
An object reference is required for the non-static field, method, or property 'The_Levels.W1L1.levelCompleted'
The form i'm working with is "W1L1", and "LevelMenu" is the menu form. Thanks in advance
You basically need a reference to your instance of LevelMenu.
So when you create your "W1L1" form, you might just pass the LevelMenu to it.
public class W1L1
{
private readonly LevelMenu _levelMenu;
public W1L1(LevelMenu levelMenu)
{
this._levelMenu = levelMenu;
}
//Where you want to enable the button
this._levelMenu.button2.Enabled = true;
}
It's not the best solution, in an architectural way, but it works.
But it would be better if you create a more OOP way for enabling the button of the next level.
When you open the next level open it as a separate object as a new form. Now when the level is completed you can access the public controls on that form from the originating class. Something like this might help:
LevelMenu NextLevel = new LevelMenu();
public event Action levelCompleted;
if (levelCompleted != null)
levelCompleted();
NextLevel.button2.Enabled = true;
here's what I did I hope this helps
I created 2 Forms
Form1 = where menu is (buttons), Form2 = the game level (i.e. level 1)
then in Form2 I added an even LevelCompleted that will notify form1 that the player completed the level
//add this to form2
//the delegate
public delegate void LevelCompleted(Int32 level);
//the event
public event LevelCompleted LevelCompletedEvent;
then on Form1 (the menu form) when you create an instance of Form2 (which has the event) subscribe to it and create a handler, in my case I added it after i created the instance of Form2
private void button1_CLick(object sender, EventArgs e)
{
Form2 level1 = new Form2();
level1.LevelCompletedEvent += new Form2.LevelCompleted(level1_LevelCompletedHandler);
level1.Show();
}
//and this is the handler method
void level1_LevelCompletedHandler(int level)
{
//the logic for controlling the button states
// the level parameter can be used to indicate what is the current level completed.
if(level == 1)
{
button1.Enabled = false;
button2.Enabled = true;
}
}
Note: that in Form2 (the game level) I created a field gameOver that can be used if he did not complete the game
If in case he is permitted to go to next level, You must raise the event in this form to notify Form1 (the menu)
that he (the user) completed the level and Form1 will execute the method level1_LevelCompletedHandler(int level).
I know this is not well explained but I hope I can give you an idea on the event.
I have a project with requirements as below,
Login form opens up and asks for user name and password.
Login Successful - Login form closes and another main form opens and all the functionalities will be added here.
In the main form there is a Call button when clicked on it, it will pop a dial pad.
When the number is entered on the dial pad and clicked "ok", control comes back to the same main form.
When logout is clicked, It wil take me to the login screen again.
For this can anybody explain me the following points:
How do I tranfer the control from one form to another?
I have to make sure when user clicks on the close 'x' , I have to log out and close the windows?
Neeed some rough class information.
Thanks in advance.
This is what i used earlier to carry data from one form to other
public partial class DialPad : Form
{
public MainGUI guiObject;
public DialPad(MainGUI mG)
{
InitializeComponent();
guiObject = mG;
}
By the sounds of it your dialler form should be a dialog..
class MyDiallerDialog : Form
{
public String DialledNumber
{
get { return this.txtNumber.Text; } // Or however the form stores its number...
}
}
class MyMainForm : Form
{
void btnCall_Click(object sender, EventArgs e)
{
using (var dialog = new MyDiallerDialog())
{
if (dialog.ShowDialog() == DialogResult.OK)
{
String number = dialog.DialledNumber;
// do something interesting with the number...
}
}
}
}
For your point no. 2
I have to make sure when user clicks
on the close 'x' , I have to log out
and close the windows?
In the event FormClosing of the form, take a look at e.ClosingReason.
So if user closes using Close Button (X), then ClosingReason would be UserClosing. So check that and then write appropriate code therein.
How do I tranfer the control from one
form to another?
For e.g
If you want to get the number in main form from Dialpad form.
1st in the contructor of main form
public static MainForm instance = null;
public string numberInMainForm = null;
public MainForm()
{
instance = this;
}
now in your dialpad form, when user enters the number, you can pass the number (or any other variable.) to main form from the dialpad form directly.
In dialpad form just write:
MainForm.instance.numberInMainForm = number;
thats it. You are done !!
let us assume you 1st form is loginform,
Suppose User press OK on the login form, so on
OK_click()
event call another form.
suppose your name of the another form is MainForm.cs then you can call using...
MainForm mf = new Mainform()
Suppose you want to close the login form when user press OK of your logIn form you can keep the order in following way..
private void OK_Click(object sender, EventArgs e)
{
. . .
// your validations
//return bool (true or false ) to confirm you have complted validations
MainForm mf = new Mainform();
mf.show(); // or you can use mf.ShowDialog();
. . .
. . .
this.close();
}
When you will close the MainForm,its control will come directly to the next line after mf.show();
To close any form use
this.close() command.
I hope this will help you ands you can start working on your project now.
EDIT:
Add a new class file named commondata.cs and in that use static variables like
public static string myString = "";
You can keep all the static functions and variables in the common file like commonData.cs so that you can modify its value from anywhere and can be used from anywhere.
Before closing your current form store the information in the static myString so even if u close the current form related information will be stored in myString & you can access it in any form using commonData.myString command.
string temp = commonData.myString;
Regards,
Sangram Nandkhile.