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.
Related
I have a form populated with an array of userControls that is created from the main form. I need to be able to access this array of userControls from the main form once the popup has been closed when a button is pressed. If I fill out the forms and then press the button on the main form without closing the popup, the values are present. However, if I close the popup window, the values are not present. My main form is static so I can use it's variables in other forms.
Code for the popup:
public ScanChannel[] controls;
public ScanListSetup()
{
InitializeComponent();
int numChans = Convert.ToInt32(Form1.Self.numChannels.Text);
controls = new ScanChannel[numChans];
// Create the UserControls
for(int i = 0; i < numChans; i++)
{
controls[i] = new ScanChannel();
}
// Place them
for (int i = 0; i < numChans; i++)
{
controls[i].Location = new Point(13,(35+25*(i)));
this.Controls.Add(controls[i]);
}
doneButton.Location = new Point(82, 35 + (25 * (numChans + 1)));
this.Size =new Size(280, 110 + (25 * (numChans + 1)));
}
private void doneButton_Click(object sender, EventArgs e)
{
Form1.Self.setChannelsToScan(controls);
}
I need to access the controls array in the main form. The code for the main form is as follows:
private ScanChannel[] channelsToScan;
private void configureScanListButton_Click(object sender, EventArgs e)
{
var form = new ScanListSetup();
form.Show(this);
scanListConfigured = true;
this.channelsToScan = new ScanChannel[Convert.ToInt32(numChannels.Text)];
}
public void setChannelsToScan(ScanChannel[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
this.channelsToScan[i] = arr[i];
}
}
private void scanButton_Click(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("Test: " + this.channelsToScan[0].getDeviceType());
// THIS PRINTS AN EMPTY STRING
}
So, the Debug writeLine outputs the correct value if I click the scanButton while the popup form is still open. However, if I close the form after clicking the doneButton on the popup form, the Debug writeLine outputs Test: with nothing else.
Any help with this would be greatly appreciated. Thanks.
Your problem essentially boils down to sending data from a secondary window (your 'pop-up' window) to the main window from where it was created. It doesn't matter whether you're working with Windows Control objects or simple data types like string, so I'm going to use a simple example to illustrate how to handle such a situation.
Let's assume you have a Main form that looks like this. It has an OPEN button and a TextBox.
When you click OPEN, it opens up this secondary input window (your pop-up) which looks like this:
Now the idea is this. You click OPEN and opens the Input form, and lets the user enter some text into the TextBox there. Once you click the OK button, it should close the Input window, and display the text entered by the user in the Main window. Remember that at this point the Input window is closed, which is equivalent to your situation.
So I'd make use of Delegates to accomplish this goal. A delegate lets you transfer data between windows which is what you want.
In my Main I'd declare a public delegate with a signature like this:
public delegate void DataTransfer(string data);
That is, this delegate represents a method that takes in a single string parameter, and has void return type. The idea is to let the secondary Input window 'call' a method in the Main, and that method takes in a string parameter. So, if there was a way for us to call a method that resides in the Main from Input, and pass a string, we can then take the user input text in the Input window, and pass it to the Main window. With me so far?
Now, if I write a method like this in the Main, and let it be called from Input, that should accomplish our goal. Here, txtDisplay is the TextBox in the Main form.
public void ReceiveInput(string data)
{
txtDisplay.Text = data;
}
To accomplish this, I would define a delegate of type DataTransfer in the Main form like below, and register the ReceiveInput() method to it. Your Main form code behind should look like this:
public delegate void DataTransfer(string data);
public partial class MainForm : Form
{
public DataTransfer transferDelegate;
InputForm inputForm = null;
public MainForm()
{
InitializeComponent();
transferDelegate += new DataTransfer(ReceiveInput);
}
public void ReceiveInput(string data)
{
txtDisplay.Text = data;
}
private void BtnOpen_Click(object sender, EventArgs e)
{
inputForm = new InputForm(transferDelegate);
inputForm.Show();
}
}
BtnOpen is the OPEN button in the Main form, and when it's clicked, it passes the delegate to the Input form, then opens it. So, accordingly, we need to now modify our Input form:
public partial class InputForm : Form
{
DataTransfer transferDel;
public InputForm(DataTransfer del)
{
InitializeComponent();
transferDel = del;
}
private void BtnOK_Click(object sender, EventArgs e)
{
string data = txtInput.Text;
transferDel.Invoke(data);
Close();
}
}
Here, we modify the constructor so that it takes in a delegate of type DataTransfer, and sets it to the local instance of the same type. Then, at the click of BtnOK on the Input form, we take in the text input by user, and pass that text to the said delegate and invoke it. 'Invoking' is the same as calling the method in the Main form. At this point, you can Clsoe() the Input window as shown above, and you'd still have access to the user input string data from your Main form.
You can use this same approach, and instead of strings you can pass around Controls. However, it's not the best approach to pass around a bunch of controls back and forth, so ideally you would extract the data you need from those controls in your pop-up, and pass only the said data instead of the whole controls.
EDIT: After OP posted the erroneous code.
OK, so here's your issue. The testUserControl class is not a regular class but a control element derived from UserControl. In otherwise, a GUI element. You shouldn't use GUI elements to pass data around. Because, when you do your controlArr[i].getText();, it tries to get the text from the textItem, but textItem is a TextBox Control which doesn't exist at this point because you closed your window. Remember, you do the delegate.Invoke() only once, and at that point *you must send ALL the data back to your main window*.
What you should do is, simply define a class to hold ALL the data you want to pass to your main. For example something like this:
public class DataToPass
{
public string TextBoxText { get; set; }
public string SomeOtherData { get; set; }
// Other stuff you want...
}
Now, instead of passing an array of testUserControl, pass an array of DataToPass. That way, at the Main form you don't have to do the following:
controlArr[i].getText();
Instead you'd simply do something like:
controlArr[i].TextBoxText;
where controlArr now is an array of type DataToPass.
Simply, passing a control derived from UserControl is not a good idea. Just create one class that is capable of holding ALL the data you want to pass and pass it back to the main once.
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.
This question might sound simple but I can't find the answer i'm looking for.
I have a Login_Form and a Main_Form.
Once I log into the Main_Form I just make it visible and I activate it because I don't want my Login_Form to close.
My question is, is there a way to close both forms at the same time from the Main_Form?
The this.Close(); will only close the current form.
if (access)
{
Main_Form mainForm = new Main_Form();
mainForm.Visible = true;
mainForm.Activate();
}
This is where I Instantiate the main_form how can I pass a reference to the login_form?
Thanks in advance and remember the Login_Form must remain open until I close it from the Main_Form!
Feedback
After looking at which of your answers I would use I found out about the Application.Close() Method Which closes all the forms. Should have taught about this before posting here thanks everyone.
If your Main form has a reference to the Login form you can call the close method on it. How you do that is up to you.
You could pass the reference in to the Main from FROM the login form when you show it.
You could keep a global reference to the Login Form. (think singleton)
any other way you can think of
For example:
public class MainForm : Form
{
Form loginform;
public MainForm(Form loginForm)
{
this.loginForm = loginForm;
}
public void CloseForms()
{
loginForm.Close();
this.Close();
}
}
In your Active() method, just pass the login form in. Alternatively you can use the code above, and just pass this into the constructor instead of the Active() method.
public class MainForm : Form
{
Form loginform;
public Active(Form loginForm)
{
this.loginForm = loginForm;
}
public void CloseForms()
{
loginForm.Close();
this.Close();
}
}
//from the LOGIN form
if (access)
{
Main_Form mainForm = new Main_Form();
mainForm.Visible = true;
mainForm.Activate(this); //this is a reference to the current form. LOGIN in this case
}
If you have a reference to the login form then call Close on that form.
Login_Form.Close()
You will have modify the constructor of Main_Form to accept login form instance as a parameter
You can also use the AddOwnedForm Method.
From above link:
When a form is owned by another form, it is closed or hidden with the
owner form. For example, consider a form named Form2 that is owned by
a form named Form1. If Form1 is closed or minimized, Form2 is also
closed or hidden. Owned forms are also never displayed behind their
owner form. You can use owned forms for windows such as find and
replace windows, which should not be displayed behind the owner form
when the owner form is selected.
Code:
Form loginForm = new Form();
this.AddOwnedForm(loginForm);
loginForm.Show();
Edit:
Form mainForm = new Form();
mainForm.Visible = true;
mainForm.AddOwnedForm(this);
mainForm.Activate();
now if you close the mainForm it will close both forms.
You could just use Application.Exit(); not Application.Close();
I'm new to C# and would like to allow to Windows forms to comminicate with each other. I googled bubbling in C# but it wasn't much help. What are some good ways I can learn bubbling?
EDIT: I want to have an options form that is shown/created when my user clicks on Edit->Preferances. I then want the settings the user changed in the options form to be relayed to the main form.
Two approaches:
Put properties on your preferences form and access them from the main form when the user clicks OK.
if (preferenceForm.ShowDialog() == DialogResult.OK)
{
this.Color = preferenceForm.UserSelectedColor;
//etc...
}
Send your preference form a delegate from the main form and let the preference form call it with the appropriate changes.
class FormSettings
{
object Color {get, set}
}
class MainForm
{
...
void ChangeSettings(FormSettings newSettings)
{ ... }
void EditPreferences_Click(...)
{
...
EditPreferencesForm editPreferences = new EditPreferencesForm(this.ChangeSettings)
editPreferences.ShowDialog();
}
}
class EditPreferencesForm
{
...
ChangeSettingsDelegate changeSettings;
FormSettings formSettings;
void OkButton_Click(...)
{
changeSettings(formSettings);
}
}
You don't state as much, but is the main form also the form that contains the Edit->Preferences menu? If so, you are already at the correct point in the code
// This is the event handler in the main form
private void mnuEditPreferencesClicked...
{
FrmPreferences frmPreferences = new FrmPreferences();
frmPreferences.ShowDialog(this);
// Preferences saved, implement changes to main form here
}
If the preferences form is not generated from the main form, fire off an event when the preferences form closes, and have the main form handle the event that way.
I'm new to C# and trying to write a simple GUI Unit Test with NUnit and NUnitForms. I want to test if a click on a button opens a new Form.
My application has two forms, the main form (Form1) with a button that opens a new form (Password):
private void button2_Click(object sender, EventArgs e)
{
Password pw = new Password();
pw.Show();
}
The source for my Test looks like this:
using NUnit.Framework;
using NUnit.Extensions.Forms;
namespace Foobar
{
[TestFixture]
public class Form1Test : NUnitFormTest
{
[Test]
public void TestNewForm()
{
Form1 f1 = new Form1();
f1.Show();
ExpectModal("Enter Password", "CloseDialog");
// Check if Button has the right Text
ButtonTester bt = new ButtonTester("button2", f1);
Assert.AreEqual("Load Game", bt.Text);
bt.Click();
}
public void CloseDialog()
{
ButtonTester btnClose = new ButtonTester("button2");
btnClose.Click();
}
}
}
The NUnit output is:
NUnit.Extensions.Forms.FormsTestAssertionException : expected 1 invocations of modal, but was invoked 0 times (Form Caption = Enter Password)
The Button Text check is successfull. The problem is the ExpectModal method. I've also tried it with the Form's name but without success.
Does anyone know what might be wrong?
I figured it out myself. There are two ways Windows Forms can be displayed:
Modal: "A modal form or dialog box must be closed or hidden before you can continue working with the rest of the application"
Modeless: "... let you shift the focus between the form and another form without having to close the initial form. The user can continue to work elsewhere in any application while the form is displayed."
Modeless Windows are opened with the Show() method and Modal ones with ShowDialog(). NUnitForms can only track Modal Dialogs (that's also why the method is named 'ExpectModal').
I changed every "Show()" to "ShowDialog()" in my source code and NUnitForms worked fine.
I would only change your source code to use ShowDialog() if you want your forms to actually be opened as Modal dialogs.
You are correct in that NUnitForms supports "Expect Modal", but does not have an "Expect Non-Modal". You can implement this yourself with relative ease using the FormTester class. FormTester is an extension class available from the latest repository for NUnitForms. You pass in the string of the .Name property of the form you are checking to see if it is shown.
public static bool IsFormVisible(string formName)
{
var tester = new FormTester(formName);
var form = (Form) tester.TheObject;
return form.Visible;
}