Wywołanie formy pierwszej z innej formy po podaniu hasła

0

Witam, mam problem z wywołaniem formy pierwszej w innej formie w języku C#. Jedną z form uzbroiłem w hasło, po podaniu dobrego hasła forma główna powinna się otwierać. W środowisku niby się otwiera, ale jak uruchamiam plik exe to wywala błąd "Odwołanie do obiektu nie zostało ustawione na wystąpienie obiektu". Oto fragment kodu:

 public partial class Form4 : Form
    {
        Form1 form1;
        public Form4(Form1 form1)
        {
            this.form1 = form1;
            InitializeComponent();
            this.FormClosing += new FormClosingEventHandler(Form4_FormClosing);
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string haslo="";
            haslo = textBox1.Text;
            if (haslo == "haslo")
            {
                form1.ShowDialog();
            }
            else
            {
                MessageBox.Show("Podałeś złe hasło", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }
        private void Form4_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            e.Cancel = true;
        }
0
Jordan napisał(a):
public partial class Form4 : Form
{
    Form1 form1;

 (...)    
}

powinno pomóc

public partial class Form4 : Form
{
    Form1 form1 = new Form1();

 (...)
}
0

Pokaż jak tworzysz instancję Form4

0

Szymon niestety nie pomogło.

public partial class Form4 : Form
    {
        Form1 form1 = new Form1();
        public Form4(Form1 form1)
        {
            this.form1 = form1;
            InitializeComponent();
            this.FormClosing += new FormClosingEventHandler(Form4_FormClosing);
            
        } 
0
Sarrus napisał(a):

Pokaż jak tworzysz instancję Form4

0

Sarrus pokazałem już kod z Form4. Nigdzie indziej nie używam nic z Form4

0

Ale gdzieś jej obiekt jest tworzony. Chociażby w program.cs

0

w program cs mam tylko to

 static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

0

Czyli Form1 jest tą główną forma. Coś masz mocno zagmatwane bo ta się normalnie pojawia jako pierwsza, a Ty ją pokazujesz w Form4 jako okno dialogowe. Wrzuć na Pastebin kod wszystkich formatek.

0

pokaż mi kod z Form1 wywołujący Form4. U mnie działa, tylko, że ja użyłem

public Form4() 
{
//  this.form1 = form1;
InitializeComponent();
this.FormClosing += new FormClosingEventHandler(Form4_FormClosing);
}

reszta kodu skopiowana od Ciebie.

0

w form1 nie wywołuje form4. co do kodu form1 to mam tylko tyle:

public Form1()
        {
            this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
            InitializeComponent(); 
}
0

to co Form4 samo się otwiera? przyłączam się do prośby @Sarrus o kod aplikacji

0

Użyj pastebina dostępnego na 4programmers (menu) i wklej tam cały kod, bo to co dajesz to są jakieś bezużyteczne fragmenty kodu, które same w sobie poprawne.

0

wybaczcie, źle powiedziałem. wywołuje form4 w ten sposób:

 private void Form1_Load(object sender, EventArgs e)
        {
            Form4 form4 = new Form4(this);
            form4.Owner = this;
            form4.ShowDialog();
        }
0

cały kod z 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;
using System.IO;

namespace Piecyk
{
    public partial class Form1 : Form
    {
        public bool godz;
        public int i = 0;
        public string start, stop;

        public Form1()
        {
            this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
            InitializeComponent();

            string folderName = @"C:\regaly";
            string pathString = System.IO.Path.Combine(folderName, "pomocnicze");
            System.IO.Directory.CreateDirectory(pathString);
            
        }


        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
            {
                if (MessageBox.Show("Czy na pewno chcesz zakończyć?",
                               "Zakończenie programu",
                                MessageBoxButtons.YesNo,
                                MessageBoxIcon.Question) == DialogResult.No) 
                    e.Cancel = true;

                string path3 = @"C:\regaly\pomocnicze\zmiana.txt";
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(path3, false))
                {
                    file.Write("");
                }
                string path4 = @"C:\regaly\pomocnicze\razem.txt";
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(path4, false))
                {
                    file.Write("");
                }
               
            }
        

        private void button1_Click(object sender, EventArgs e)
        {
            button3.Visible = false;
            button7.Visible = false;
            i = i + 1;

            double s63, s64, l05, b13, c26;
            double razem, zm, all;
            double razemall;
            double temp = 0; ;

            

                if (godz == false){
                    label1.Text = DateTime.UtcNow.AddHours(1).ToShortTimeString();
                    label6.Text = DateTime.UtcNow.AddHours(2).ToShortTimeString();
                }

            godz = false;
            stop = label6.Text;
            start = label1.Text;
            label4.Text = Convert.ToString(i);
            label7.Text = DateTime.Now.ToShortDateString();
            MessageBox.Show("Dodałeś regał", "Uwaga", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

            s63 = double.Parse(textBox1.Text);
            s64 = double.Parse(textBox2.Text);
            l05 = double.Parse(textBox3.Text); 
            b13 = double.Parse(textBox4.Text);
            c26 = double.Parse(textBox5.Text);

            
            razem = s63 + s64 + l05 + b13 + c26;
            label14.Text = razem.ToString();

            string reg = label4.Text;
            string dzis = DateTime.Now.ToShortDateString();
            string path = @"C:\regaly\" + dzis + ".txt";
            string path2 = @"C:\regaly\pomocnicze\" + dzis + ".txt";
            string path3 = @"C:\regaly\pomocnicze\zmiana.txt";
            string path4 = @"C:\regaly\pomocnicze\razem.txt";

            using (StreamReader sr = new StreamReader(path4))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    temp = double.Parse(line);
                }
            }

            using (System.IO.StreamWriter file = new System.IO.StreamWriter(path4, false))
            {

                razemall = temp + razem;
                label18.Text = razemall.ToString();
                file.Write(razemall);
            }

            label18.Text = Convert.ToString(razemall);

          
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(path, true))
            {

                file.WriteLine("Regal nr" + reg + ":");
                file.WriteLine();
                file.WriteLine("S63:" + s63);
                file.WriteLine("S64:" + s64);
                file.WriteLine("L05:" + l05);
                file.WriteLine("B13:" + b13);
                file.WriteLine("C26:" + c26);
                file.WriteLine();
                file.WriteLine("razem:" + razem);
                file.WriteLine("razem wszystkich:" + razemall);
                file.WriteLine("=====================");
                file.Close();
            }

            using (System.IO.StreamWriter files = new System.IO.StreamWriter(path2, true))
            {

                files.Write("Regal nr" + reg + " " + start + "-" + stop);



                if (comboBox1.Text == "1")
                {
                    files.WriteLine(" (1)");
                }
                else if (comboBox1.Text == "2")
                {
                    files.WriteLine(" (2)");
                }
                else if (comboBox1.Text == "3")
                {
                    files.WriteLine(" (3)");
                }

                files.Close();
            }
            richTextBox1.LoadFile(path2, RichTextBoxStreamType.PlainText);
            richTextBox2.LoadFile(path, RichTextBoxStreamType.PlainText);

            


                 textBox1.Text = "0";
                 textBox2.Text = "0";
                 textBox3.Text = "0";
                 textBox4.Text = "0";
                 textBox5.Text = "0";


                 if (checkBox1.Checked == true)
                 {
                     
                     zm = 0;
                     using (StreamReader sr = new StreamReader(path3))
                     {
                         string line;
                         while ((line = sr.ReadLine()) != null)
                         {
                             zm = double.Parse(line);
                         }
                     }

                     using (System.IO.StreamWriter file = new System.IO.StreamWriter(path3, false))
                     {
                         
                         all = zm + razem;
                         label16.Text = all.ToString();
                         file.Write(all);
                     }
                 }
                 checkBox1.Checked = false;
        }



        private void button2_Click(object sender, EventArgs e)
        {
            button3.Visible = true;
            string reg = label4.Text;
            string dzis = DateTime.Now.ToShortDateString();
            string path = @"C:\regaly\" + dzis + ".txt";
            string path2 = @"C:\regaly\pomocnicze\" + dzis + ".txt";
            richTextBox1.LoadFile(path2, RichTextBoxStreamType.PlainText);
            richTextBox2.LoadFile(path, RichTextBoxStreamType.PlainText);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            button3.Visible = false;
            Form2 form2 = new Form2(this);
            form2.Owner = this;
            form2.ShowDialog();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            string dzis = DateTime.Now.ToShortDateString();
            string path = @"C:\regaly\" + dzis + ".txt";
            string path2 = @"C:\regaly\pomocnicze\" + dzis + ".txt";
            string path3 = @"C:\regaly\pomocnicze\zmiana.txt";
            string path4 = @"C:\regaly\pomocnicze\razem.txt";

            if (MessageBox.Show("Czy na pewno chcesz wyczyścić plik? Dane z dnia "+ dzis + " zostaną utracone!",
                              "Wyczyść plik",
                               MessageBoxButtons.YesNo,
                               MessageBoxIcon.Warning) == DialogResult.Yes)
            {


                using (System.IO.StreamWriter file = new System.IO.StreamWriter(path3, false))
                {
                    file.Write("");
                }
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(path2, false))
                {
                    file.Write("");
                }
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(path, false))
                {
                    file.Write("");
                }

                using (System.IO.StreamWriter file = new System.IO.StreamWriter(path4, false))
                {
                    file.Write("");
                }

                button3.Visible = false;
                label4.Text = "1";
                i = 0;
            }
     
        }

        private void button5_Click(object sender, EventArgs e)
        {
            Form3 form3 = new Form3(this);
            form3.Owner = this;
            form3.ShowDialog();

        }



        private void button6_Click(object sender, EventArgs e)
        {
            button7.Visible = true;
            richTextBox1.ReadOnly = false;
            richTextBox2.ReadOnly = false;
        }

        private void button7_Click(object sender, EventArgs e)
        {
            
            string dzis = DateTime.Now.ToShortDateString();
            string path = @"C:\regaly\" + dzis + ".txt";
            string path2 = @"C:\regaly\pomocnicze\" + dzis + ".txt";

            richTextBox1.SaveFile(path2, RichTextBoxStreamType.PlainText);
            richTextBox2.SaveFile(path, RichTextBoxStreamType.PlainText);
            button7.Visible = false; 
            richTextBox1.ReadOnly = true;
            richTextBox2.ReadOnly = true;

            

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Form4 form4 = new Form4(this);
            form4.Owner = this;
            form4.ShowDialog();
        }



    }

    }


0

Ok działa, dzięki wielkie za pomoc :)

1

Tak jest nieco lepiej. Zamiast przekazywać form1 do form4 lepiej jest udostępnić informację w form4 czy hasło zostało wpisane poprawnie.

Form4:

 public partial class Form4 : Form
    {
        public bool HasloPoprawne {get; private set;} //odczyt z form1 ale zapis tylko z form4

        public Form4()
        {
            this.HasloPoprawne = false; //ustawienie domyślne
            InitializeComponent();
            this.FormClosing += new FormClosingEventHandler(Form4_FormClosing);
 
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string haslo="";
            haslo = textBox1.Text;
            if (haslo == "haslo")
            {
                this.HasloPoprawne = true; //zostawiamy wiadomość że hasło zostało wpisane poprawnie
                this.Close(); //i zamykamy okno
            }
            else
            {
                MessageBox.Show("Podałeś złe hasło", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }

W Form1:

        private void Form1_Load(object sender, EventArgs e)
        {
            Form4 form4 = new Form4();
            form4.Owner = this;
            form4.ShowDialog(); // metoda ta zakończy działanie po zamknięciu form4
            if (!form4.HasloPoprawne) //sprawdzamy wiadomość czy jest ok
                 this.Close(); //jeżeli nie to zamykamy to okno i całą aplikację
        }

EDIT:
Zamiast ustawiać jakąś zmienną możesz też użyć DialogResult:
http://msdn.microsoft.com/pl-pl/library/c7ykbedk(v=vs.110).aspx

Ale na tym etapie to już wedle uznania.

0

ok dzięki za podopowiedzi i pomoc, pomogłeś mi bardzo. Zastosuje tą metode którą napisałeś. Co do Twojego komentarza na temat zamykania form4 krzyżykiem - zablokowałem możliwość zamknięcia okna krzyżykiem w taki sposób:

 private void Form4_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
                e.Cancel = true;
        }
0

A tak faktycznie. Nie pisałem w WInFormsach dawno. No to w takim razie pytanie jak użytkownik może zrezygnować z wpisania hasła?

0

Dodałem przycisk i po jego naciśnięciu wywołuje Application.exit :)

1 użytkowników online, w tym zalogowanych: 0, gości: 1