开发者

Winform appears twice

开发者 https://www.devze.com 2023-01-29 18:03 出处:网络
I am working on a personal project in winforms just to gain some experience in it since I\'ve never had the chance to work with it before. So, I\'m quite the n00b when it comes to Winforms. This is th

I am working on a personal project in winforms just to gain some experience in it since I've never had the chance to work with it before. So, I'm quite the n00b when it comes to Winforms. This is the error I'm encountering:

In form BudgetTracker, I have a button called 'AddCat'. Below is the form's constructor and the button's click eventHandler:

        public form_BudgetTracker()
        {
            InitializeComponent();
            setEvents();
        }

        public void setEvents()
        {
            this.btn_AddCat.Click += new System.EventHandler(this.btn_AddCat_Click);
        }

        private void btn_AddCat_Click(object sender, EventArgs e)
        {
            form_NewCat NewCatForm = new form_NewCat();
            var NewCatFormResult = NewCatForm.ShowDialog();
            NewCatForm.Show();
        }

In the NewCat form that comes up, I have a Cancel button. Code:

        public form_NewCat()
        {
            InitializeComponent();
            SetEvents();
        }

        private void SetEvents()
        {
            this.btn_Add.Click += new System.EventHandler(this.btn_Add_Click);
            this.btn_Cancel.Click += new System.EventHandler(this.btn_Cancel_Click);
        }

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

The problem I'm facing is, when I click Add, the new form comes up. At this point, if I click Cancel, the form disappears but instantly a new instance of the form appears. I then click cancel again, and the form disappears. What part of my code is making the form appear twice. I checked the contructors etc, but couldn't figure i开发者_开发知识库t out. Any help or pointers would be appreciated.

PS - As I mentioned, I'm new to winforms programming, so any cues or pointers would be appreciated as well.


private void btn_AddCat_Click(object sender, EventArgs e)
{
    form_NewCat NewCatForm = new form_NewCat();
    var NewCatFormResult = NewCatForm.ShowDialog(); // <-- opens the first time
    NewCatForm.Show();                              // <-- opens the second time
}


Judging from your code, you're simply showing the form twice!!!

        form_NewCat NewCatForm = new form_NewCat(); 
        var NewCatFormResult = NewCatForm.ShowDialog(); 
        NewCatForm.Show(); 

The second line shows the form and blocks the method until DialogResult is set, then the third line shows the form without blocking the method.

Simply remove the third line!


Try stepping through the code using the F8 key instead of running it, or hitting F5. It will show you line by line what it's about to execute.


delete NewCatForm.Show();

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号