Как открыть вторую форму windows forms

Добавление форм в проект. Взаимодействие между формами в Windows Forms и Visual C#

Добавление форм. Взаимодействие между формами

Последнее обновление: 31.10.2015

Чтобы добавить еще одну форму в проект, нажмем на имя проекта в окне Solution Explorer (Обозреватель решений) правой кнопкой мыши и выберем
Add(Добавить)->Windows Form…

добавление новой формы

Дадим новой форме какое-нибудь имя, например, Form2.cs:

создание новой формы

Итак, у нас в проект была добавлена вторая форма. Теперь попробуем осуществить взаимодействие между двумя формами. Допустим, первая форма
по нажатию на кнопку будет вызывать вторую форму. Во-первых, добавим на первую форму Form1 кнопку и двойным щелчком по кнопке перейдем в файл кода. Итак,
мы попадем в обработчик события нажатия кнопки, который создается по умолчанию после двойного щелчка по кнопке:

private void button1_Click(object sender, EventArgs e)
{

}

Теперь добавим в него код вызова второй формы. У нас вторая форма называется Form2, поэтому сначала мы создаем объект данного класса, а потом для его
отображения на экране вызываем метод Show:

private void button1_Click(object sender, EventArgs e)
{
	Form2 newForm = new Form2();
	newForm.Show();
}

Теперь сделаем наоборот — чтобы вторая форма воздействовала на первую. Пока вторая форма не знает о существовании первой. Чтобы это исправить, надо
второй форме как-то передать сведения о первой форме. Для этого воспользуемся передачей ссылки на форму в конструкторе.

Итак перейдем ко второй форме и перейдем к ее коду — нажмем правой кнопкой мыши на форму и выберем View Code (Просмотр кода). Пока он пустой и
содержит только конструктор. Поскольку C# поддерживает перегрузку методов, то мы можем создать несколько методов и конструкторов с разными
параметрами и в зависимости от ситуации вызывать один из них. Итак, изменим файл кода второй формы на следующий:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HelloApp
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        public Form2(Form1 f)
        {
            InitializeComponent();
            f.BackColor = Color.Yellow;
        }
    }
}

Фактически мы только добавили здесь новый конструктор public Form2(Form1 f), в котором мы получаем первую форму и устанавливаем ее фон
в желтый цвет. Теперь перейдем к коду первой формы, где мы вызывали вторую форму и изменим его на следующий:

private void button1_Click(object sender, EventArgs e)
{
	Form2 newForm = new Form2(this);
	newForm.Show();
}

Поскольку в данном случае ключевое слово this представляет ссылку на текущий объект — объект Form1, то при создании второй формы она будет получать ее (ссылку)
и через нее управлять первой формой.

Теперь после нажатия на кнопку у нас будет создана вторая форма, которая сразу изменит цвет первой формы.

Мы можем также создавать объекты и текущей формы:

private void button1_Click(object sender, EventArgs e)
{
	Form1 newForm1 = new Form1();
	newForm1.Show();
		
	Form2 newForm2 = new Form2(newForm1);
	newForm2.Show();
}

При работе с несколькими формами надо учитывать, что одна из них является главной — которая запускается первой в файле Program.cs.
Если у нас одновременно открыта куча форм, то при закрытии главной закрывается все приложение и вместе с ним все остальные формы.

You need to handle an event on Form1 that is raised as a result of user interaction. For example, if you have a «Settings» button that the user clicks in order to show the settings form (Form2), you should handle the Click event for that button:

private void settingsButton_Click(Object sender, EventArgs e)
{
    // Create a new instance of the Form2 class
    Form2 settingsForm = new Form2();

    // Show the settings form
    settingsForm.Show();
}

In addition to the Show method, you could also choose to use the ShowDialog method. The difference is that the latter shows the form as a modal dialog, meaning that the user cannot interact with the other forms in your application until they close the modal form. This is the same way that a message box works. The ShowDialog method also returns a value indicating how the form was closed.


When the user closes the settings form (by clicking the «X» in the title bar, for example), Windows will automatically take care of closing it.

If you want to close it yourself before the user asks to close it, you can call the form’s Close method:

this.Close();


Содержание

  • Условие задания
  • Выполнение
    • 1. Создать приложение типа Windows Forms Application
    • 2. Разработка главной формы приложения
    • 3. Создание второстепенной формы
    • 4. Разработка второстепенной формы
    • 5. Программирование событий клика на кнопках OK и Cancel формы Form2
    • 6. Вызов формы Form2 из главной формы приложения
    • 7. Выполнение приложения
  • Связанные темы

Поиск на других ресурсах:

Условие задания

Разработать демонстрационное приложение, осуществляющее вызов из главной формы второстепенной формы по схеме, изображенной на рис. 1. Приложение реализует взаимодействие между различными формами, которыми могут быть диалоговые окна любой сложности.

В главной форме Form1 разместить:

  • элемент управления типа Label для вывода результата возврата из второстепенной формы;
  • элемент управления типа Button для вызова второстепенной формы.

Во второстепенной форме Form2 разместить:

  • элемент управления типа Label для вывода заголовка формы;
  • два элемента управления типа Button для обеспечения подтверждения или неподтверждения выбора (действия) во второстепенной форме.

C# Схема взаимодействия между формами

Рис. 1. Схема взаимодействия между формами

 


Выполнение

1. Создать приложение типа Windows Forms Application

Запустить Microsoft Visual Studio 2010. Пример создания нового приложения типа Windows Forms Application подробно описывается здесь.

Сохранить проект в произвольной папке.

После создания приложения у нас есть одна форма. Программный код формы размещен в файле «Form1.cs» (рис. 2).

C# Windows Forms Главная форма

Рис. 2. Главная форма приложения Form1

 

2. Разработка главной формы приложения

Из палитры элементов управления Toolbox выносим на форму:

  • элемент управления типа Button;
  • элемент управления типа Label.

Автоматически создаются два объекта-переменные с именами button1 и label1.
В элементе управления типа Button свойство Text установить в значение «Show Form 2«.
В элементе управления типа Label свойство Text установить в значение «Result = «.
После внесенных изменений главная форма Form1 приложения будет иметь вид как показано на рисунке 3.

C# Windows Forms форма

Рис. 3. Главная форма приложения после внесенных изменений

 

3. Создание второстепенной формы

Для создания второстепенной формы в C# можно воспользоваться несколькими способами.

Способ 1.
Для добавления формы №2 в проект этим способом нужно вызвать команду (рис. 4)

Project -> Add Windows Form...

C# Windows Forms команда "Add Windows Form..."

Рис. 4. Команда «Add Windows Form…» для добавления новой формы в проект

В результате откроется окно «Add New Item — Windows Forms Application1«. В этом окне выбираем элемент «Windows Form» (рис. 5). Оставляем имя формы как «Form2.cs«.

Windows Form C# добавление новой формы

Рис. 5. Окно добавления новой формы к проекту

После нажатия на кнопке «Add» новая форма будет добавлена к проекту (рис. 6).

C# Windows Forms форма Form2 файл "Form2.cs"Рис. 6. Новосозданная форма Form2 и файл «Form2.cs«

Способ 2.

Также новую форму можно добавить к проекту с помощью соответствующей команды из контекстного меню (рис. 7).
Последовательность действий следующая:

  • в Solution Explorer сделать клик правой кнопкой «мышки» на названии приложения WindowsFormsApplication1;
  • выбрать подменю Add;
  • в подменю Add выбрать команду «Windows Form…«.

C# Windows Forms новая форма Solution Explorer

Рис. 7. Добавление новой формы из Solution Explorer

В результате откроется точно такое же окно как на рисунке 5.

 

4. Разработка второстепенной формы

Следующим шагом есть разработка второстепенной формы. Используя средства панели инструментов Toolbox создаем второстепенную форму Form2 как показано на рисунке 8. Такое построение формы соответствует условию задачи. Таким же образом, на Form2 имеем элементы управления label1, butto1, button2.

C# Windows Forms Второстепенная форма Form2

Рис. 8. Второстепенная форма Form2

 

5. Программирование событий клика на кнопках OK и Cancel формы Form2

Программируем событие клика на кнопке OK. Подробный пример программирования события клика на кнопке OK описывается здесь.

В программный код обработчика события button1_Click() (кнопка «OK«) вписываем следующую строку:

this.DialogResult = DialogResult.OK;

это значит, что результат возврата из формы Form2 есть «OK«.
Точно так же в обработчике события button2_Click вписываем:

this.DialogResult = DialogResult.Cancel;

это значит выбор кнопки «Cancel» (button2).



После внесенных изменений листинг программного кода файла «Form2.cs» будет иметь следующий вид:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
  public partial class Form2 : Form
  {
    public Form2()
    {
      InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
      this.DialogResult = DialogResult.OK;
    }

    private void button2_Click(object sender, EventArgs e)
    {
      this.DialogResult = DialogResult.Cancel;
    }
  }
}

Переход к программному коду формы Form2 (файл «Form2.cs«) можно осуществить с помощью Solution Explorer. Для этого в Solution Explorer вызываем контекстное меню для формы Form2 и из этого меню выбираем команду «View Code» (рис. 9).

Visual Studio C# Команда "View Code"

Рис. 9. Команда «View Code» для перехода в режим программного кода

 

6. Вызов формы Form2 из главной формы приложения

Согласно с условием задачи, для вызова Form2 из Form1 нужно запрограммировать событие клика на кнопке «Show Form 2«.

Программный код обработчика события будет иметь следующий вид:

...
private void button1_Click(object sender, EventArgs e)
{
    Form2 f = new Form2(); // создаем объект типа Form2

    if (f.ShowDialog() == DialogResult.OK) // вызов диалогового окна формы Form2
    {
        label1.Text = "Result = OK!"; 
    }
    else
    {
         label1.Text = "Result = Cancel!";
    }
}
...

В листинге, приведенном выше, сначала создается экземпляр класса типа Form2. В операторе условного перехода if осуществляется вызов диалогового окна формы Form2 с помощью строки

f.ShowDialog();

Функция ShowDialog() выводит окно формы и держит его открытым до тех пор, пока пользователь не сделает какой-либо выбор. После выбора пользователем той или иной команды, окно закрывается с кодом возврата. Происходит проверка кода возврата с известными константами класса DialogResult. После проверки выводится сообщение о действии, выбранном пользователем в Form2 (элемент управления label2).

Листинг всего программного кода формы Form1 следующий

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Form2 f = new Form2();
            if (f.ShowDialog() == DialogResult.OK)
            {
                label1.Text = "Result = OK!";
            }
            else
            {
                label1.Text = "Result = Cancel!";
            }
        }
    }
}

 

7. Выполнение приложения

После выполненных действий можно выполнять приложение и исследовать его работу.


Связанные темы

  • Delphi. Создание новой формы и подключение ее к главной форме программы
  • C++ Builder. Пример создания и вызова новой формы из главной формы приложения
  • Пример создания и вызова диалогового окна в MS Visual Studio 2010 — C++ (MFC)


Для начала необходимо поставить все точки над i т.е. прописать какая у тебя форма главная, а какая нет,для того чтобы главную форму определить главной прописываете вот что:

C#
1
2
3
4
5
        void ShowChildForm(Form form)
        {
            form.MdiParent = this;
            form.Show();
        }

для того чтобы определить дочернюю форму необходимо 2а раза кликнуть по вашей «главной» форме на которой будет кнопка (Но не по кнопке) у вас появится вот что:

C#
1
2
3
4
private void Spravochnik_Load(object sender, EventArgs e)
        {
            
        }

Spravochnik_Load — вместо этого будет ваше название, оно прописывается само.
в скобках вы прописываете вот что:

C#
1
2
fSecond form = new fSecond();
ShowChildForm(form);

fSecond — название вашей дочерней формы.

И теперь уже два раза кликайте по вашей кнопке появится:

C#
1
2
3
4
5
private void button1_Click(object sender, EventArgs e)
{
            fSecond form = new fSecond();
            ShowChildForm(form);
}

Ну вот теперь должна появляться ваша дочерняя форма при нажатии на кнопку на главной форме.

Добавлено через 3 минуты
для того чтобы определить дочернюю форму необходимо 2а раза кликнуть по вашей «главной» форме на которой будет кнопка (Но не по кнопке) у вас появится вот что:

C#
1
2
3
4
private void Spravochnik_Load(object sender, EventArgs e)
{
 
}

Spravochnik_Load — вместо этого будет ваше название, оно прописывается само.
в скобках вы прописываете вот что:

C#
1
2
fSecond form = new fSecond();
ShowChildForm(form);

fSecond — название вашей дочерней формы.

Извиняюсь вот это писать не нужно!!!!!

Here I will explain how to open a second from using a first form in Windows Forms. Before that I will explain group boxes and picture boxes in Windows Forms.

Step 1: Login form

There is a login from when I enter a password and username and then the page goes directly to another page named form2.

Login from

Step 2: Add a new form

Now go to Solution Explorer and select your project and right-click on it and select a new Windows Forms form and provide the name for it as form2.

Add a new form

And the new form is:

new form

Step 3: Coding

Now click the submit button and write the code.

Coding

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Text;  
  7. using System.Windows.Forms;  
  8. using System.Data.SqlClient;  
  9. namespace First_Csharp_app  
  10. {  
  11.     public partial class Form1 : Form  
  12.     {  
  13.         public Form1()  
  14.         {  
  15.             InitializeComponent();  
  16.         }  
  17.         private void button1_Click(object sender, EventArgs e)  
  18.         {  
  19.             try  
  20.             {  
  21.                 if (!(usertxt.Text == string.Empty))  
  22.                 {  
  23.                     if (!(passtxt.Text == string.Empty))  
  24.                     {  
  25.                         String str = «server=MUNESH-PC;database=windowapp;UID=sa;password=123»;  
  26.                         String query = «select * from data where username = ‘» + usertxt.Text + «‘and password = ‘» + this.passtxt.Text + «‘»;  
  27.                         SqlConnection con = new SqlConnection(str);  
  28.                         SqlCommand cmd = new SqlCommand(query, con);  
  29.                         SqlDataReader dbr;  
  30.                         con.Open();  
  31.                         dbr = cmd.ExecuteReader();  
  32.                         int count = 0;  
  33.                         while (dbr.Read())  
  34.                         {  
  35.                             count = count + 1;  
  36.                         }  
  37.                         if (count == 1)  
  38.                         {  
  39.                             this.hide();  
  40.                             Form2 f2 = new form2();   
  41.                             f2.ShowDialog();  
  42.                         }  
  43.                         else if (count > 1)  
  44.                         {  
  45.                             MessageBox.Show(«Duplicate username and password»«login page»);  
  46.                         }  
  47.                         else  
  48.                         {  
  49.                             MessageBox.Show(» username and password incorrect»«login page»);  
  50.                         }  
  51.                     }  
  52.                     else  
  53.                     {  
  54.                         MessageBox.Show(» password empty»«login page»);  
  55.                     }  
  56.                 }  
  57.                 else  
  58.                 {  
  59.                     MessageBox.Show(» username empty»«login page»);  
  60.                 }  
  61.                   
  62.             }  
  63.             catch (Exception es)  
  64.             {  
  65.                 MessageBox.Show(es.Message);  
  66.             }  
  67.         }  
  68.     }  

Step 4: Output

When you click on the submit button a new form will be opened named form2.

Here I will explain how to open a second from using a first form in Windows Forms. Before that I will explain group boxes and picture boxes in Windows Forms.

Step 1: Login form

There is a login from when I enter a password and username and then the page goes directly to another page named form2.

Login from

Step 2: Add a new form

Now go to Solution Explorer and select your project and right-click on it and select a new Windows Forms form and provide the name for it as form2.

Add a new form

And the new form is:

new form

Step 3: Coding

Now click the submit button and write the code.

Coding

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Text;  
  7. using System.Windows.Forms;  
  8. using System.Data.SqlClient;  
  9. namespace First_Csharp_app  
  10. {  
  11.     public partial class Form1 : Form  
  12.     {  
  13.         public Form1()  
  14.         {  
  15.             InitializeComponent();  
  16.         }  
  17.         private void button1_Click(object sender, EventArgs e)  
  18.         {  
  19.             try  
  20.             {  
  21.                 if (!(usertxt.Text == string.Empty))  
  22.                 {  
  23.                     if (!(passtxt.Text == string.Empty))  
  24.                     {  
  25.                         String str = «server=MUNESH-PC;database=windowapp;UID=sa;password=123»;  
  26.                         String query = «select * from data where username = ‘» + usertxt.Text + «‘and password = ‘» + this.passtxt.Text + «‘»;  
  27.                         SqlConnection con = new SqlConnection(str);  
  28.                         SqlCommand cmd = new SqlCommand(query, con);  
  29.                         SqlDataReader dbr;  
  30.                         con.Open();  
  31.                         dbr = cmd.ExecuteReader();  
  32.                         int count = 0;  
  33.                         while (dbr.Read())  
  34.                         {  
  35.                             count = count + 1;  
  36.                         }  
  37.                         if (count == 1)  
  38.                         {  
  39.                             this.hide();  
  40.                             Form2 f2 = new form2();   
  41.                             f2.ShowDialog();  
  42.                         }  
  43.                         else if (count > 1)  
  44.                         {  
  45.                             MessageBox.Show(«Duplicate username and password»«login page»);  
  46.                         }  
  47.                         else  
  48.                         {  
  49.                             MessageBox.Show(» username and password incorrect»«login page»);  
  50.                         }  
  51.                     }  
  52.                     else  
  53.                     {  
  54.                         MessageBox.Show(» password empty»«login page»);  
  55.                     }  
  56.                 }  
  57.                 else  
  58.                 {  
  59.                     MessageBox.Show(» username empty»«login page»);  
  60.                 }  
  61.                   
  62.             }  
  63.             catch (Exception es)  
  64.             {  
  65.                 MessageBox.Show(es.Message);  
  66.             }  
  67.         }  
  68.     }  

Step 4: Output

When you click on the submit button a new form will be opened named form2.

I have form which is opened using ShowDialog Method. In this form i have a Button called More.
If we click on More it should open another form and it should close the current form.

on More Button’s Click event Handler i have written the following code

MoreActions objUI = new MoreActions (); 
objUI.ShowDialog();
this.Close();

But what is happening is, it’s not closing the first form. So, i modified this code to

MoreActions objUI = new MoreActions (); 
objUI.Show();
this.Close();

Here, The second form is getting displayed and within seconds both the forms getting closed.

Can anybody please help me to fix issue. What i need to do is, If we click on More Button, it should open another form and close the first form.

Any kind of help will be really helpful to me.

asked Oct 19, 2010 at 3:03

Dinesh's user avatar

1

In my opinion the main form should be responsible for opening both child form. Here is some pseudo that explains what I would do:

// MainForm
private ChildForm childForm;
private MoreForm moreForm;

ButtonThatOpenTheFirstChildForm_Click()
{
    childForm = CreateTheChildForm();
    childForm.MoreClick += More_Click;
    childForm.Show();
}

More_Click()
{
    childForm.Close();
    moreForm = new MoreForm();
    moreForm.Show();
}

You will just need to create a simple event MoreClick in the first child. The main benefit of this approach is that you can replicate it as needed and you can very easily model some sort of basic workflow.

answered Oct 19, 2010 at 5:38

Johann Blais's user avatar

Johann BlaisJohann Blais

9,3296 gold badges45 silver badges64 bronze badges

3

If I got you right, are you trying like this?

alt text

into this?
alt text

in your Form1, add this event in your button:

    // button event in your Form1
    private void button1_Click(object sender, EventArgs e)
    {
        Form2 f2 = new Form2();
        f2.ShowDialog(); // Shows Form2
    }

then, in your Form2 add also this event in your button:

    // button event in your Form2
    private void button1_Click(object sender, EventArgs e)
    {
        Form3 f3 = new Form3(); // Instantiate a Form3 object.
        f3.Show(); // Show Form3 and
        this.Close(); // closes the Form2 instance.
    }

answered Oct 19, 2010 at 3:59

yonan2236's user avatar

yonan2236yonan2236

13.2k32 gold badges94 silver badges139 bronze badges

2

ok so I used this:

public partial class Form1 : Form
{
    private void Button_Click(object sender, EventArgs e)
    {
        Form2 myForm = new Form2();
        this.Hide();
        myForm.ShowDialog();
        this.Close();
    }
}

This seems to be working fine but the first form is just hidden and it can still generate events. the «this.Close()» is needed to close the first form but if you still want your form to run (and not act like a launcher) you MUST replace it with

this.Show();

Best of luck!

Funlamb's user avatar

Funlamb

5495 silver badges18 bronze badges

answered Jul 15, 2013 at 20:17

user2584967's user avatar

1

I would use a value that gets set when more button get pushed closed the first dialog and then have the original form test the value and then display the the there dialog.

For the Ex

  1. Create three windows froms
  2. Form1 Form2 Form3
  3. Add One button to Form1
  4. Add Two buttons to form2

Form 1 Code

 public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private bool DrawText = false;

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 f2 = new Form2();
        f2.ShowDialog();
        if (f2.ShowMoreActions)
        {
            Form3 f3 = new Form3();
            f3.ShowDialog();
        }

    }

Form2 code

 public partial class Form2 : Form
 {
        public Form2()
        {
            InitializeComponent();
        }

        public bool ShowMoreActions = false;
        private void button1_Click(object sender, EventArgs e)
        {
            ShowMoreActions = true;
            this.Close();
        }


        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }

Leave form3 as is

answered Oct 19, 2010 at 3:19

rerun's user avatar

rerunrerun

24.7k6 gold badges48 silver badges77 bronze badges

Try this..

//button1 will be clicked to open a new form
private void button1_Click(object sender, EventArgs e)
{
    this.Visible = false;     // this = is the current form
    SignUp s = new SignUp();  //SignUp is the name of  my other form
    s.Visible = true;
}

Arun Singh's user avatar

Arun Singh

1,5284 gold badges19 silver badges43 bronze badges

answered Oct 1, 2012 at 5:26

fmp's user avatar

1

private void Button1_Click(object sender, EventArgs e)
{
    NewForm newForm = new NewForm();    //Create the New Form Object
    this.Hide();    //Hide the Old Form
    newForm.ShowDialog();    //Show the New Form
    this.Close();    //Close the Old Form
}

answered Oct 4, 2019 at 17:29

Robert Karamagi's user avatar

1

you may consider this example

//Form1 Window
//EventHandler
Form1 frm2 = new Form1();
{
    frm2.Show(this); //this will show Form2
    frm1.Hide();  //this Form will hide
}

answered Aug 14, 2017 at 1:22

Ramgy Borja's user avatar

Ramgy BorjaRamgy Borja

2,2042 gold badges18 silver badges39 bronze badges

For example, you have a Button named as Button1. First click on it it will open the EventHandler of that Button2 to call another Form you should write the following code to your Button.

your name example=form2.

form2 obj=new form2();

obj.show();

To close form1, write the following code:

form1.visible=false;
or
form1.Hide();

Vimal CK's user avatar

Vimal CK

3,5131 gold badge25 silver badges47 bronze badges

answered Apr 5, 2017 at 5:16

Mahmud Yusuf Sani MahmudCodes's user avatar

You could try adding a bool so the algorithm would know when the button was activated. When it’s clicked, the bool checks true, the new form shows and the last gets closed.

It’s important to know that forms consume some ram (at least a little bit), so it’s a good idea to close those you’re not gonna use, instead of just hiding it. Makes the difference in big projects.

answered May 28, 2018 at 4:28

Rafael's user avatar

You need to control the opening of sub forms from a main form.

In my case I’m opening a Login window first before I launch my form1. I control everything from Program.cs. Set up a validation flag in Program.cs. Open Login window from Program.cs. Control then goes to login window. Then if the validation is good, set the validation flag to true from the login window. Now you can safely close the login window. Control returns to Program.cs. If the validation flag is true, open form1. If the validation flag is false, your application will close.

In Program.cs:

   static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        /// 

        //Validation flag
        public static bool ValidLogin = false;

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);


            Application.Run(new Login());

            if (ValidLogin)
            {
                Application.Run(new Form1());
            }
        }

    }

In Login.cs:

       private void btnOK_Click(object sender, EventArgs e)
        {
            if (txtUsername.Text == "x" && txtPassword.Text == "x")
            {
                Program.ValidLogin = true;
                this.Close();
            }
            else
            {
                MessageBox.Show("Username or Password are incorrect.");
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

answered Oct 25, 2019 at 23:31

Dominic Isaia's user avatar

Use this.Hide() instead of this.Close()

answered Aug 12, 2020 at 20:31

izzetot's user avatar

Do this to Program.cs

using System;

namespace ProjectName 
{
    public class Program
    {
        [STAThread]
        public static void Main(string[] args) 
        {
            Application.EnableVisualStyles();
            Application.SetDefaultCompatibleTextRendering(false);

            new Form1().Show();

            Application.Run();
        }
    }
}

answered Apr 3, 2022 at 19:11

Madhav Balakrishnan Nair's user avatar

I have form which is opened using ShowDialog Method. In this form i have a Button called More.
If we click on More it should open another form and it should close the current form.

on More Button’s Click event Handler i have written the following code

MoreActions objUI = new MoreActions (); 
objUI.ShowDialog();
this.Close();

But what is happening is, it’s not closing the first form. So, i modified this code to

MoreActions objUI = new MoreActions (); 
objUI.Show();
this.Close();

Here, The second form is getting displayed and within seconds both the forms getting closed.

Can anybody please help me to fix issue. What i need to do is, If we click on More Button, it should open another form and close the first form.

Any kind of help will be really helpful to me.

asked Oct 19, 2010 at 3:03

Dinesh's user avatar

1

In my opinion the main form should be responsible for opening both child form. Here is some pseudo that explains what I would do:

// MainForm
private ChildForm childForm;
private MoreForm moreForm;

ButtonThatOpenTheFirstChildForm_Click()
{
    childForm = CreateTheChildForm();
    childForm.MoreClick += More_Click;
    childForm.Show();
}

More_Click()
{
    childForm.Close();
    moreForm = new MoreForm();
    moreForm.Show();
}

You will just need to create a simple event MoreClick in the first child. The main benefit of this approach is that you can replicate it as needed and you can very easily model some sort of basic workflow.

answered Oct 19, 2010 at 5:38

Johann Blais's user avatar

Johann BlaisJohann Blais

9,3296 gold badges45 silver badges64 bronze badges

3

If I got you right, are you trying like this?

alt text

into this?
alt text

in your Form1, add this event in your button:

    // button event in your Form1
    private void button1_Click(object sender, EventArgs e)
    {
        Form2 f2 = new Form2();
        f2.ShowDialog(); // Shows Form2
    }

then, in your Form2 add also this event in your button:

    // button event in your Form2
    private void button1_Click(object sender, EventArgs e)
    {
        Form3 f3 = new Form3(); // Instantiate a Form3 object.
        f3.Show(); // Show Form3 and
        this.Close(); // closes the Form2 instance.
    }

answered Oct 19, 2010 at 3:59

yonan2236's user avatar

yonan2236yonan2236

13.2k32 gold badges94 silver badges139 bronze badges

2

ok so I used this:

public partial class Form1 : Form
{
    private void Button_Click(object sender, EventArgs e)
    {
        Form2 myForm = new Form2();
        this.Hide();
        myForm.ShowDialog();
        this.Close();
    }
}

This seems to be working fine but the first form is just hidden and it can still generate events. the «this.Close()» is needed to close the first form but if you still want your form to run (and not act like a launcher) you MUST replace it with

this.Show();

Best of luck!

Funlamb's user avatar

Funlamb

5495 silver badges18 bronze badges

answered Jul 15, 2013 at 20:17

user2584967's user avatar

1

I would use a value that gets set when more button get pushed closed the first dialog and then have the original form test the value and then display the the there dialog.

For the Ex

  1. Create three windows froms
  2. Form1 Form2 Form3
  3. Add One button to Form1
  4. Add Two buttons to form2

Form 1 Code

 public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private bool DrawText = false;

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 f2 = new Form2();
        f2.ShowDialog();
        if (f2.ShowMoreActions)
        {
            Form3 f3 = new Form3();
            f3.ShowDialog();
        }

    }

Form2 code

 public partial class Form2 : Form
 {
        public Form2()
        {
            InitializeComponent();
        }

        public bool ShowMoreActions = false;
        private void button1_Click(object sender, EventArgs e)
        {
            ShowMoreActions = true;
            this.Close();
        }


        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }

Leave form3 as is

answered Oct 19, 2010 at 3:19

rerun's user avatar

rerunrerun

24.7k6 gold badges48 silver badges77 bronze badges

Try this..

//button1 will be clicked to open a new form
private void button1_Click(object sender, EventArgs e)
{
    this.Visible = false;     // this = is the current form
    SignUp s = new SignUp();  //SignUp is the name of  my other form
    s.Visible = true;
}

Arun Singh's user avatar

Arun Singh

1,5284 gold badges19 silver badges43 bronze badges

answered Oct 1, 2012 at 5:26

fmp's user avatar

1

private void Button1_Click(object sender, EventArgs e)
{
    NewForm newForm = new NewForm();    //Create the New Form Object
    this.Hide();    //Hide the Old Form
    newForm.ShowDialog();    //Show the New Form
    this.Close();    //Close the Old Form
}

answered Oct 4, 2019 at 17:29

Robert Karamagi's user avatar

1

you may consider this example

//Form1 Window
//EventHandler
Form1 frm2 = new Form1();
{
    frm2.Show(this); //this will show Form2
    frm1.Hide();  //this Form will hide
}

answered Aug 14, 2017 at 1:22

Ramgy Borja's user avatar

Ramgy BorjaRamgy Borja

2,2042 gold badges18 silver badges39 bronze badges

For example, you have a Button named as Button1. First click on it it will open the EventHandler of that Button2 to call another Form you should write the following code to your Button.

your name example=form2.

form2 obj=new form2();

obj.show();

To close form1, write the following code:

form1.visible=false;
or
form1.Hide();

Vimal CK's user avatar

Vimal CK

3,5131 gold badge25 silver badges47 bronze badges

answered Apr 5, 2017 at 5:16

Mahmud Yusuf Sani MahmudCodes's user avatar

You could try adding a bool so the algorithm would know when the button was activated. When it’s clicked, the bool checks true, the new form shows and the last gets closed.

It’s important to know that forms consume some ram (at least a little bit), so it’s a good idea to close those you’re not gonna use, instead of just hiding it. Makes the difference in big projects.

answered May 28, 2018 at 4:28

Rafael's user avatar

You need to control the opening of sub forms from a main form.

In my case I’m opening a Login window first before I launch my form1. I control everything from Program.cs. Set up a validation flag in Program.cs. Open Login window from Program.cs. Control then goes to login window. Then if the validation is good, set the validation flag to true from the login window. Now you can safely close the login window. Control returns to Program.cs. If the validation flag is true, open form1. If the validation flag is false, your application will close.

In Program.cs:

   static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        /// 

        //Validation flag
        public static bool ValidLogin = false;

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);


            Application.Run(new Login());

            if (ValidLogin)
            {
                Application.Run(new Form1());
            }
        }

    }

In Login.cs:

       private void btnOK_Click(object sender, EventArgs e)
        {
            if (txtUsername.Text == "x" && txtPassword.Text == "x")
            {
                Program.ValidLogin = true;
                this.Close();
            }
            else
            {
                MessageBox.Show("Username or Password are incorrect.");
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

answered Oct 25, 2019 at 23:31

Dominic Isaia's user avatar

Use this.Hide() instead of this.Close()

answered Aug 12, 2020 at 20:31

izzetot's user avatar

Do this to Program.cs

using System;

namespace ProjectName 
{
    public class Program
    {
        [STAThread]
        public static void Main(string[] args) 
        {
            Application.EnableVisualStyles();
            Application.SetDefaultCompatibleTextRendering(false);

            new Form1().Show();

            Application.Run();
        }
    }
}

answered Apr 3, 2022 at 19:11

Madhav Balakrishnan Nair's user avatar

Понравилась статья? Поделить с друзьями:

Вот еще несколько интересных статей:

  • Как открыть дисковод с помощью клавиатуры на windows 10
  • Как открыть второй экран на windows 10 сочетание клавиш
  • Как открыть диспетчер задач поверх всех окон windows 10
  • Как открыть дисковод на ноутбуке леново без кнопки windows 10
  • Как открыть дисковод на ноутбуке асус без кнопки windows 10

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии