Show form by button - c#

I want to make a management application with a Windows Forms form and I want to display one login form and when the login button is clicked, the second form should appear.
I tried this:
MainProgramm.BringToFrot();
How can I do that?

If you have a FormMain and you want to call a different form from it, you should create an instance of the second form and show it on the screen (as per #Tvde1 comment):
SecondForm secondForm = new SecondForm();
secondForm.Show();
If you want the new form to act as a dialog box, you can use:
secondForm.ShowDialog(this);

What you pretty much to do is add the following code in the Click action of the button that you want:
MainProgram mainProgram=new MainProgram();
mainProgram.ShowDialog();
Or if you prefer
MainProgram mainProgram=new MainProgram();
mainProgram.Show();

You can use Show() method to display form.
MainProgram mainProgram = new MainProgram();
mainProgram.Show();

There is a typo in your example code. Maybe you should try:
MainProgramm.BringToFront(); // add the missing 'n' letter
then add a new line like this:
MainProgramm.Show();

Hook into the OnLoad() method of the main form, and transfer control to the login form modally with the .ShowDialog() method.
For example:
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
var dlg = new LoginForm();
dlg.UserID = Environment.UserName;
if (dlg.ShowDialog() != DialogResult.OK)
{
this.Close();
}
var id = dlg.UserID;
toolStripStatusLabel1.Text = $"Login: {id}";
}
}

Related

How to close Opened Form and open new Form on button click

I have two Winforms open at present.Out of the two one is Login form.Now as per my requirement ,if the user entered right credentials then these two opened forms needs to be closed and new form should be opened.
Means I have to close opened winforms and open new Winform on button click event of Login form.
Here i am not knowing exactly which windows are open because login form window is coming from menu button click event which is present on every form
Please help me.Thanks in advance..
Try this:
foreach (Form f in Application.OpenForms)
{
f.Close();
}
OR using for loop:
for (int i = Application.OpenForms.Count - 1; i >= 0; i--)
{
Application.OpenForms[i].Close();
}
OR create a list of forms:
List<Form> openForms = new List<Form>();
foreach (Form f in Application.OpenForms)
openForms.Add(f);
foreach (Form f in openForms)
{
f.Close();
}
As per you requirement, close all other forms except login form and then show that form.
foreach (Form f in Application.OpenForms)
{
if(f.Name!="frmLogin") //Closing all other
f.Close(); //forms
}
Now activate the login form.
frmLogin.Show();
frmLogin.Focus();
Application.OpenForms gets a collection of open forms owned by the application. Read more about Application.OpenForms.
You can iterate over the Application.OpenForms collection and close that you need.
you can't use foreach to close the forms as suggested in earlier replies. This is because foreach cannot be used to alter the enumerated forms list (when you Close() them, you will get a run-time error). Even if you use a for loop, you'll have to check that the main form is also not closed by mistake...
for(int i=0; i< Application.OpenForms.Count; i++)
{
Form f = Application.OpenForms[i];
if(f != this)
f.Close();
}
Instead, you can try out the below logic.
Where are these two forms getting loaded from? is it from a main form? I am assuming that both are being displayed using Form.Show() method.
In the login form login button handler, I'd accept a reference to the main form. when validation succeeds, I'd call a function LoginSuccessful() in the parent form, which would iterate through the open forms and close them.
public partial class FormMain : Form
{
LoginForm loginForm;
OtherForm otherForm;
public FormMain()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
loginForm = new LoginForm(this);
otherForm = new OtherForm();
loginForm.Show();
otherForm.Show();
}
public void LoginSuccessful()
{
loginForm.Close();
otherForm.Close();
OtherForm thirdForm = new OtherForm();
thirdForm.Show();
}
}
LoginForm code as below:
public partial class LoginForm : Form
{
FormMain parent;
bool bLoginSuccessful = false;
public LoginForm(FormMain parent)
{
InitializeComponent();
this.parent = parent;
}
private void button1_Click(object sender, EventArgs e)
{
bLoginSuccessful = true;
Thread.Sleep(5000);
if (bLoginSuccessful == true)
parent.LoginSuccessful();
}
}
This should help you in solving your problem... Granted, it isn't the best way... It all depends upon your approach. If you are more detailed in your requirement, I can probably think out a better way.
In your login form, make default constructor private and add a new constructor and a private member like this:
private Form _callerform;
private LoginForm()
{
InitializeComponent();
}
public LoginForm(Form caller)
{
InitializeComponent();
}
Now, in the click event of button on LoginForm, try something like this:
Form SomeOtherForm = new Form();
SomeOtherForm.Show();
// Hide login and caller form
Hide();
_callerForm.Hide();
Now, you have hidden a couple of forms and opened a new one. When the user closes the application, you need to close other forms too. So,
void Application_ApplicationExit(object sender, EventArgs e)
{
foreach (Form form in Application.OpenForms)
{
form.Close();
}
}

How to open a Form Dialog from a MDI child form (MDI application)

I have a MDI main form, a menu item that shows a child form (let's call it frmEmployees), inside this form a Button (btnNew...), how do I open from here a form as Dialog (frmNewEmployee); I mean, frmEmployees can't be reached until frmNewEmployee has been closed.
// Main_Form_Load
Main_Form.IsMdiContainer = true;
From a menu item in main form, I open frmEmployees
// MenuItem_Click
frmEmployees frmEmp = new frmEmployees();
frmEmp.MdiParent = this;
frmEmp.Show();
from a Button, I open the another form
// newButton_Click
frmNewEmployee frmNE = new frmNewEmployee();
frmNE.MdiParent = this.MdiParent;
//frmNE.Show(); // OK, but allows return to frmEmployees
frmNE.ShowDialog(); // here comes the problem
Is there any method to block frmEmployees while frmNewEmployee is open?
Thanks in advance!
Don't set frmNE.mdiParent. Let the instance be a child of frmEmployees. To restate, don't set the mdiParent property and call frmNE.ShowDialog() and the blocked form will be frmEmployee.
namespace ModalTest
{
using System;
using System.Windows.Forms;
public partial class frmMain : Form
{
frmEmployees frmEmp = new frmEmployees();
frmNewEmployee frmNE = new frmNewEmployee();
public frmMain()
{
InitializeComponent();
IsMdiContainer = true;
}
private void btnGo_Click(object sender, EventArgs e)
{
frmEmp.MdiParent = this;
frmEmp.Show();
}
private void button1_Click(object sender, EventArgs e)
{
frmNE.MdiParent = frmEmp.MdiParent;
frmEmp.Hide();
frmNE.Show();
}
}
}
Essentially what I did is assign the third form frmNE to the parent of the second form frmEMP, then use frmEmp.Hide() to hide the form from view. Using '.ShowDialog()', as I mentioned above, forces your third form to become modal, and thus requiring it to be satisfied before execution can continue.

C# change textbox text on a modal form from an another form

I'm trying to change a text on a TextBox on a modal main form by clicking on a button from an another active form, need help.
Main form *Modal mode
public void changetext(){
textbox1.text = textnew;
}
form2 *active form
private void btnChange_Click(object sender, EventArgs e)
{
mainform form1 = new mainform;
public String textnew = "NEW"
form1.changetext();
this.close
}
Ive tired to use this code but it gives me the error of : Invoke or BeginInvoke cannot be called on a control until the window handle has been created.:
public void LabelWrite(string value)
{
if (InvokeRequired)
Invoke(new LabelWriteDelegate(LabelWrite), value);
else
{
textBox1.Text = value;
}
}
delegate void LabelWriteDelegate(string value);
i think there's a logic issue. If i understand your requirement, you have a main form which contains a search textbox. When the user launch a serach, you open a modal form where all possible results are displayed. The user selects the value he wants and then you get the result in the main form. Is this correct? If so you should do it this way:
Create a public property on the modal form which contains the result.
Either create a public property or create a new constructor on the modal form to pass the query.
On the main form, you can access the public properties of the modal form as long as it is not disposed.
For instance:
var result = null;
var modal = new ModalForm(query);
if(modal.ShowDialog() == DialogResult.OK) // This means the user has selected a value
{
result = modal.SelectedResult;
}
modal.Close();
modal.Dispose();
The easiest way is to pass the new text to the modal window.
For example:
Main form Modal mode
public void changetext(String textnew){
textbox1.text = textnew;
}
form2 active form
private void btnChange_Click(object sender, EventArgs e)
{
mainform form1 = new mainform;
form1.changetext("NEW");
this.close
}
If I were you I would also change form names, they are a little bit confusing.
P.S. I still don't get what is this.close is needed for.

C# Winform close opened window when call other window

How can I close an opened window when I call a new window? That means I want only 1 child window at the time. I don't allow multi-window.
public partial class Main_Usr : Form
{
public Main_Usr()
{
InitializeComponent();
this.IsMdiContainer = true;
if (Program.IsFA) barSubItem_Ordre.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
Ordre_Liste f = new Ordre_Liste();
f.MdiParent = this;
f.Show();
}
private void barButtonItem_CreateOrdre_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
Program.AllerRetour = "Ordre Aller";
Ordre_Fiche f = new Ordre_Fiche();
f.MdiParent = this;
f.Show();
}
private void barButtonItem_OrdreListe_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
Ordre_Liste f = new Ordre_Liste();
f.MdiParent = this;
f.Show();
}
private void barButtonItem_CreateOrdRet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
Program.AllerRetour = "Ordre Retour";
Ordre_Fiche f = new Ordre_Fiche();
f.MdiParent = this;
f.Show();
}
}
There are different ways to implement pseudo masterpage:
You can create BaseForm form with desired layout. Then inherit other forms from this BaseForm and provide custom content.
You can create MainForm form with desired layout. Then create content controls as UserControls and show them in panel.
You can create MasterUserControl with desired layout. Then create content controls by inheriting from MasterUserControl (they will have same layout). Then use your main form as browser for displaying different content controls like pages.
EXAMPLE:
Create desired layout on Main_Usr form.
Do not set it as MdiContainer
If you want to access some controls (e.g. footer or header from child forms, set property Modifiers of those controls to protected)
Open Ordre_Liste form code and change it to inherit from Main_Usr form, instead of Form
Add custom content to Ordre_Liste form
voila! you have 'masterpage'
UPDATE (for 3rd option)
Create new user control with name MasterUserControl
Create desired layout on this control, keeping space for custom content (btw don't use TableLayoutPanels - they have issue with designer inheritance).
Create new user control with name HomeUserControl and change it to inherit from your MasterUserControl.
Open HomeUserControl designer and add custom content. Also you can modify parent controls, which has protected modifier.
On your main form place HomePageUserControl
There different ways to implement navigation between controls (aka pages). Simplest way - have menu on main form. Other way - define event 'Navigate' on master control, subscribe to that event on main form, and raise it from 'pages'.
Create Form instances on a class level.
Then you can access to them from events or methods.
Form1 f1;
Form2 f2;
void OpenForm1()
{
f1 = new Form1()
f1.Show();
}
void OpenForm2()
{
f1.Dispose(); //or Hide if you want to show it again later
f2 = new Form2();
f2.Show();
}
Like:
List<Form> openForms = new List<Form>();
foreach (Form f in Application.OpenForms)
openForms.Add(f);
foreach (Form f in openForms)
{
if (f.Name != "Menu")
f.Close();
}
Note, do NOT close them directly, becuase there will come to an error, if you would try to close (or dispose) them in the 1st foreach loop. Thats why you need to put them into a list and close them there.

Create a Login Form

I have a form that I want to provide some security on, but up to this point I've only created one form that does all of my work. I want to create a new form that pops up in front of my main form right when the application launches. Then validates the password entered against a MySQL database. I have all of the MySQL stuff down, but wondering how to make another form pop up in front of my main form which disables the main form, waits for the password form to validate, then disappears once the form is validated and lets the user perform their work. I'll also need to transfer the authenticated user's info back to my main form.
You can create a new form and then use the ShowDialog function. If you show the form from your main form it will be displayed in a modal fashion.
Create this in a login style and close the form if the user is authenticated or show an error if the username and password are incorrect.
From MSDN:
public void ShowMyDialogBox()
{
Form2 testDialog = new Form2();
// Show testDialog as a modal dialog and determine if DialogResult = OK.
if (testDialog.ShowDialog(this) == DialogResult.OK)
{
// Read the contents of testDialog's TextBox.
this.txtResult.Text = testDialog.TextBox1.Text;
}
else
{
this.txtResult.Text = "Cancelled";
}
testDialog.Dispose();
}
I prefer to use ApplicationContext for this kind of log on form <--> shell form switching behavior.
Your main method:
public static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyFancyContext());
}
And an implementation for MyFancyContext:
public class MyFancyContext : ApplicationContext
{
private LogOnForm logOnForm;
private ShellForm shellForm;
public MyFancyContext()
{
this.logOnForm = new LogOnForm();
this.MainForm = this.logOnForm;
}
protected override void OnMainFormClosed(object sender, EventArgs e)
{
if (this.MainForm == this.logOnForm
&& this.logOnForm.DialogResult == DialogResult.OK)
{
// Assume the log on form validated credentials
this.shellForm = new ShellForm();
this.MainForm = this.shellForm;
this.MainForm.Show();
}
else
{
// No substitution, so context will stop and app will close
base.OnMainFormClosed(sender, e);
}
}
}
The MainForm is the form that is currently receiving messages.
The advantage of this type of setup is that if you want to do things like hide the shell form after some idle timeout and redisplay the log on form, we have one class where this functionality takes place.
You can call showdialog(loginform) from the main form's constructor and return true if successful or change the startup for to the login form before the main form loads. Show dialog is modal.

Categories