Windows forms как открыть другую форму

Открытие другой формы C# Решение и ответ на вопрос 76872

1 / 1 / 0

Регистрация: 11.05.2009

Сообщений: 26

1

Открытие другой формы

20.12.2009, 01:25. Показов 98977. Ответов 15


Существуют два диалоговых окна: Form1 и Form2, как осуществить с помощью нажатия баттона в Form1 открытие Form2? Помогите пожалуйста, а то после Делфи очень сложно разобраться.
P.S. Подскажите также какие-нибудь учебники по Windows Forms, гугл не помогает

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Dexs

417 / 285 / 3

Регистрация: 29.07.2009

Сообщений: 1,981

20.12.2009, 01:35

2

C#
1
2
3
4
5
        private void button1_Click(object sender, EventArgs e)
        {
            Form f2 = new Form();
            f2.Show();
        }

Цитата
Сообщение от hike38
Посмотреть сообщение

Подскажите также какие-нибудь учебники по Windows Forms

http://msdn.microsoft.com/ru-ru/default.aspx



4



1 / 1 / 0

Регистрация: 11.05.2009

Сообщений: 26

20.12.2009, 02:20

 [ТС]

3

а если я хочу не создавать новую форму, а открыть уже существующую в проекте Form2, как это реализовать?



0



4331 / 1500 / 101

Регистрация: 12.04.2009

Сообщений: 2,342

20.12.2009, 02:29

4

Всмысле открыть существующую? Вы должны создать экземпляр класса Form2
Form2 f2 = new Form2();
f2.Show();



2



1 / 1 / 0

Регистрация: 11.05.2009

Сообщений: 26

20.12.2009, 02:42

 [ТС]

5

ок, спасибо, это я и имел в виду



0



yarkov_aleksei

0 / 0 / 3

Регистрация: 24.05.2012

Сообщений: 93

31.08.2013, 20:33

6

Я конечно припозднился )) но чтоб не создавать новую тему спрошу тут. Вот тот метод который вы советуете у меня не работает. Пишу так.

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
 
namespace VKPublicAdmin
{
    public partial class MainForm : Form
    {
        
        public MainForm()
        {
            InitializeComponent();
            
        }
        
        //AboutForm AbForm;
            
        private void MenuItem3_About_Click(object sender, EventArgs e)
        {
            AboutForm AbForm = new AboutForm();
            AbForm.Show();
        }
    }
}

И когда выбираю пункт меню и кликаю на нем, то ничего не происходит. Я пол дня уже голову ломаю.



0



SAUtrade

14 / 14 / 2

Регистрация: 21.10.2012

Сообщений: 140

31.08.2013, 23:31

7

Добавляешь две формы

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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 Test
{
    public partial class Parent : Form
    {
        public Parent()
        {
            InitializeComponent();
        }
 
        private void Show_Click(object sender, EventArgs e)
        {
            Child form1 = new Child();
            form1.ShowDialog();
        }
    }
}
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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 Test
{
    public partial class Child : Form
    {
        public Child()
        {
            InitializeComponent();
        }
 
        private void Close_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}



1



14 / 14 / 2

Регистрация: 21.10.2012

Сообщений: 140

31.08.2013, 23:36

8



1



yarkov_aleksei

0 / 0 / 3

Регистрация: 24.05.2012

Сообщений: 93

31.08.2013, 23:36

9

Так у меня тоже самое. И не работает. Код первой формы описан выше. Вот код второй формы.

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System;
using System.Drawing;
using System.Windows.Forms;
 
namespace VKPublicAdmin
{
    public partial class AboutForm : Form
    {
        public AboutForm()
        {
            InitializeComponent();
        }
    }
}

Не работает :`(



0



SAUtrade

14 / 14 / 2

Регистрация: 21.10.2012

Сообщений: 140

31.08.2013, 23:40

10

AbForm.Show();

C#
1
AbForm.ShowDialog();



0



0 / 0 / 3

Регистрация: 24.05.2012

Сообщений: 93

31.08.2013, 23:47

11

Вот проект. Гляньте, пожалуйста, что не так. Я второй день с Дельфей на Шарп пересесть пытаюсь. Щас за пивом пойду. Мозг сломан.



0



SAUtrade

14 / 14 / 2

Регистрация: 21.10.2012

Сообщений: 140

31.08.2013, 23:47

12

Цитата
Сообщение от yarkov_aleksei
Посмотреть сообщение

Так у меня тоже самое. И не работает. Код первой формы описан выше. Вот код второй формы.

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System;
using System.Drawing;
using System.Windows.Forms;
 
namespace VKPublicAdmin
{
    public partial class AboutForm : Form
    {
        public AboutForm()
        {
            InitializeComponent();
        }
    }
}

Не работает :`(

WindowsFormsApplication7.rar вот рабочий с меню

Выложи свой проект



0



0 / 0 / 3

Регистрация: 24.05.2012

Сообщений: 93

31.08.2013, 23:52

13

Проект открыть не могу. Че то мой SharpDev тупит. А вот экзешник ваш отрабатывает как надо. И у меня то же самое написано но не работает. В чем дело?



0



14 / 14 / 2

Регистрация: 21.10.2012

Сообщений: 140

01.09.2013, 00:12

14

В AboutForm.Disigner.cs

есть строчка this.Opacity = 0.01D;
удали ее и все будет работать и сам в дизайнере ничего никогда не пиши))

Добавлено через 38 секунд
у меня Visual Studio 2012



1



0 / 0 / 3

Регистрация: 24.05.2012

Сообщений: 93

01.09.2013, 00:18

15

SAUtrade, капец, я с 15:00 по Москве бьюсь от стол лбом. На жену рычу, чтоб не лезла, ибо раздражает все. А оказалось я дибил решил с прозрачностью поиграться :`-(. Спасибо вам огромное, не знаю как благодарить.



0



SAUtrade

14 / 14 / 2

Регистрация: 21.10.2012

Сообщений: 140

01.09.2013, 00:24

16

Цитата
Сообщение от yarkov_aleksei
Посмотреть сообщение

SAUtrade, капец, я с 15:00 по Москве бьюсь от стол лбом. На жену рычу, чтоб не лезла, ибо раздражает все. А оказалось я дибил решил с прозрачностью поиграться :`-(. Спасибо вам огромное, не знаю как благодарить.

Бывает)) Мне самому стало интересно что не так)

Добавлено через 3 минуты

Цитата
Сообщение от yarkov_aleksei
Посмотреть сообщение

решил с прозрачностью поиграться

Если с прозрачностью надо то ставь от 0,1 до 1.. Подбери значение которое нужно
И прописуй

C#
1
2
3
4
5
6
7
8
 public partial class AboutForm : Form
    {
        public AboutForm()
        {
            InitializeComponent();
Opacity = 0.8;
        }
    }



0



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

Последнее обновление: 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.
Если у нас одновременно открыта куча форм, то при закрытии главной закрывается все приложение и вместе с ним все остальные формы.

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

I am creating an application where the front end has to be a Windows Form using C++/CLI. The form is used for login purpose.

In my form, I have a register button. On click of this button, a new form should open ( closing the login form ). I was able to achieve this by the following code:

Form^ rgForm = gcnew RegisterForm;
rgForm->Show();
this->Hide(); // using this->Close() was closing the application

Now I want to have a cancel button on the register form, whose click should open the login form again and close the register form. How do I achieve that?

( I am confused with the use of this->Hide(), does it mean that the form exists, we just did not show it, and so even after the register form visibility, the login form still exists? )

Update : Now current form handle is passed into register form constructor ( storing it as a private variable with the name loginForm in RegisterForm class ).

Following is the code for cancel button click:

// RegisterForm class constructor

RegisterForm(System::Windows::Forms::Form^ f)
{
    loginForm = f;
}

// Cancel button click

private: System::Void BtnCancel_Click(System::Object^  sender, System::EventArgs^  e) 
{
     loginForm->Show();
     this->Hide();
}

On cancel button click I am getting the exception : «object not set to instance».

Can someone please help me.

Thanks.

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.

Понравилась статья? Поделить с друзьями:
  • Windows forms запретить изменение размера формы
  • Windows forms доступ к элементам другой формы
  • Windows forms для visual studio 2019 скачать
  • Windows forms всплывающее окно с вводом данных
  • Windows forms visual studio mac os